Solve the problem of C++ fopen reading files and data by line

  • 2020-06-07 04:58:22
  • OfStack

1. Existing text file:


string dataList;

Read using fopen:


FILE *fpListFile = fopen(dataList.c_str(), "r");
if (!fpListFile){
	cout << "0.can't open " << dataList << endl;
	return -1;
}

2. Read data by row:

Method 1:


char loadImgPath[1000];
while(EOF != fscanf(fpListFile, "%s", loadImgPath))
{
 ...
}

loadImgPath cannot use string type, nor can it use ES15en.c_ES17en () to receive data, otherwise the reading content is empty.

Method 2:


char buff[1000];
while(fgets(buff, 1000 ,fpListFile) != NULL)
{
 char *pstr = strtok(buff, "\n");
 ... 
}

Where buff receives data that includes a newline character, the newline character needs to be deleted before it can be used.


Related articles: