龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

C++获取文件具体方法详解

时间:2011-04-12 23:18来源:未知 作者:admin 点击:
分享到:
在这篇文章中,我们将会为大家详细介绍一下有关 C++ 获取文件的相关方法。对于刚刚接触C++编程语言不久的朋友们来说,这篇文章介绍的内容可以帮助他们解决一些在文件操作中经常

在这篇文章中,我们将会为大家详细介绍一下有关C++获取文件的相关方法。对于刚刚接触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();  

以上就是我们为大家介绍的C++获取文件相关方法。

精彩图集

赞助商链接