简体   繁体   中英

C read a specific line from a file

I need to read line x from file.txt and store it in the string 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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