C++如何获取文件

海外服务器 (460) 2015-11-24 13:30:40

对于刚刚接触C++编程语言不久的朋友们来说,这篇文章介绍的内容可以帮助他们解决一些在文件操作中经常遇到的难题。

  1. /*read File*/  
  2. char *txt = NULL;  
  3. long txtlen;  
  4. //seek to file end to calculate file length  
  5. fseek(fp,0,SEEK_END);  
  6. txtlen=ftell(fp);  
  7. //rewind to file start  
  8. rewind(fp);  
  9. //read from file  
  10. txt = new char[txtlen + 1];  
  11. if (txt != NULL)   
  12. {  
  13. fread(txt,sizeof(char),txtlen,fp);  
  14. txt[txtlen]='\0';  
  15. fv.setData(txt);  
  16. }  
  17. //close file and destroy temp array  
  18. fclose(fp);  
  19. if(txt!=NULL)  
  20. {  
  21. delete []txt;  
  22. txt = NULL;  

C++获取文件的写法:

  1. /*read File*/  
  2. ifstream in(filesrc);  
  3. if(in.fail())  
  4. {  
  5. printf("open file failed!\n");  
  6. }  
  7. else  
  8. {  
  9. string strtmp;  
  10. while (getline(in,strtmp))  
  11. {  
  12. fv.getData()+=strtmp;  
  13. fv.getData()+='\n';  
  14. }  
  15. in.close();  
THE END