简体   繁体   English

C 从文件中读取特定行

[英]C read a specific line from a file

I need to read line x from file.txt and store it in the string string我需要从file.txt读取第x行并将其存储在字符串string

I am stumped and have no idea what to do, this is what I have我很难过,不知道该怎么办,这就是我所拥有的

FILE *file = fopen("file.txt", "r");
int x = someLine;

if (file == NULL) {
    printf("Error! \n");
    strcpy(string, "ERROR");
    return;
}


fclose(file);

this is an answer a simple google search could answer.这是一个简单的谷歌搜索可以回答的答案。 However, since I'm already typing I'll go ahead and answer this.但是,因为我已经在打字了,所以我会继续回答这个问题。

http://www.codingunit.com/c-tutorial-file-io-using-text-files http://www.codingunit.com/c-tutorial-file-io-using-text-files

you need to read the lines and keep track of how many you have read.您需要阅读这些行并记录您阅读了多少行。

char buf[1000];

while (fgets(buf,1000, file) != NULL)
    printf("%s",buf);

you'll have to look into how fgets works to change this for your use, but this should easily get you to the solution.您将不得不研究 fgets 如何工作来改变它以供您使用,但这应该很容易让您找到解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM