[英]how to read specific line read from file
I have managed to read all the lines in my file to a char array but when I want to read a specific line ie line 254 as in the example below, I always get the data in the last line in my file. 我已经设法将我文件中的所有行读取到char数组但是当我想要读取特定行时,如下面的示例中的第254行,我总是在我的文件的最后一行中获取数据。 Any idea what's the problem.
知道问题是什么。 Thank you.
谢谢。 Here is sample of the code:
以下是代码示例:
while (fgets(line,2000,fp)!=NULL
{
readData [n] = line;
n++;
}
printf ("print line after %s\n",readData [254]);
You're copying the pointer every time. 你每次都在复制指针。 So at the end every entry of the
readData
array will point to the same memory. 所以最后
readData
数组的每个条目都指向相同的内存。 Try to copy the data instead: 尝试复制数据:
readData[n] = strdup(line);
And remember to free
when done. 并记得完成后
free
。 If you don't have strdup
or don't want to use it: 如果你没有
strdup
或不想使用它:
readData[n] = malloc(strlen(line) + 1);
strcpy(readData[n], line);
I'm guessing "readData" is an array of char*s, so when you say readData[n] = line
you are always setting the array to the same "buffer" of data. 我猜“readData”是一个char * s数组,所以当你说
readData[n] = line
你总是将数组设置为相同的“缓冲区”数据。
You need something a bit more like 你需要更多的东西
char buffer[numLines][colsPerLine];
char line[colsPerLine];
while (fgets(line,2000,fp)!=NULL
{
strcpy(buffer[n], line); // copy contents of line into the buffer
n++;
}
printf ("print line after %s\n",buffer[254]);
You can use seek pointer to move cursor to line no . 您可以使用搜索指针将光标移动到行号。 And then apply reading line .
然后应用阅读线。 Hope it will work.
希望它会奏效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.