C Programming - Read specific line from text file

前端 未结 2 1620
渐次进展
渐次进展 2021-01-04 23:14

Here is the code:

int main()
{
    struct vinnaren
    {
        char vinnare[20];
        int artal;
    };
    struct vinnaren v[10];
    int inputrader;
         


        
2条回答
  •  时光说笑
    2021-01-05 00:04

    With this code you can read a file line by line and hence read a specific line from the text file:

    lineNumber = x;
    
    static const char filename[] = "file.txt";
    FILE *file = fopen(filename, "r");
    int count = 0;
    if ( file != NULL )
    {
        char line[256]; /* or other suitable maximum line size */
        while (fgets(line, sizeof line, file) != NULL) /* read a line */
        {
            if (count == lineNumber)
            {
                //use line or in a function return it
                //in case of a return first close the file with "fclose(file);"
            }
            else
            {
                count++;
            }
        }
        fclose(file);
    }
    else
    {
        //file doesn't exist
    }
    

提交回复
热议问题