如何处理C语言中fopen按行读取文件时遇到的数据问题?
- 内容介绍
- 相关推荐
本文共计251个文字,预计阅读时间需要2分钟。
1. 已有文本文件:string dataList;
2.使用fopen读取:FILE *fpListFile=fopen(dataList.c_str(), r);
3.若不能打开:cout << can't open <
1、已有文本文件:
string dataList;
使用fopen读取:
FILE *fpListFile = fopen(dataList.c_str(), "r"); if (!fpListFile){ cout << "0.can't open " << dataList << endl; return -1; }
2、按行读取数据:
方法一:
char loadImgPath[1000]; while(EOF != fscanf(fpListFile, "%s", loadImgPath)) { ... }
其中,loadImgPath不能使用string类型,即使用loadImgPath.c_str()接收数据也不行,否则读取内容为空;
方法二:
char buff[1000]; while(fgets(buff, 1000 ,fpListFile) != NULL) { char *pstr = strtok(buff, "\n"); ... }
其中,buff接收的数据包括了换行符,所以在使用之前需先将删除换行符。
以上这篇解决C++ fopen按行读取文件及所读取的数据问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持自由互联。
本文共计251个文字,预计阅读时间需要2分钟。
1. 已有文本文件:string dataList;
2.使用fopen读取:FILE *fpListFile=fopen(dataList.c_str(), r);
3.若不能打开:cout << can't open <
1、已有文本文件:
string dataList;
使用fopen读取:
FILE *fpListFile = fopen(dataList.c_str(), "r"); if (!fpListFile){ cout << "0.can't open " << dataList << endl; return -1; }
2、按行读取数据:
方法一:
char loadImgPath[1000]; while(EOF != fscanf(fpListFile, "%s", loadImgPath)) { ... }
其中,loadImgPath不能使用string类型,即使用loadImgPath.c_str()接收数据也不行,否则读取内容为空;
方法二:
char buff[1000]; while(fgets(buff, 1000 ,fpListFile) != NULL) { char *pstr = strtok(buff, "\n"); ... }
其中,buff接收的数据包括了换行符,所以在使用之前需先将删除换行符。
以上这篇解决C++ fopen按行读取文件及所读取的数据问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持自由互联。

