Home > Blockchain >  how do i make operations on a specific line in a text file in c?
how do i make operations on a specific line in a text file in c?

Time:08-17

void main(void)
{
    FILE* textfile;
    char    line[1000];

    textfile = fopen("omar.txt", "r");
    if (textfile == NULL)
        return 1;

    while (fgets(line, 1000, textfile)) {
        printf(line);
    }

    fclose(textfile);
}

so this code prints the whole content of a text file , what should I do to read the third line in the file for example ?

CodePudding user response:

To read the nth line in a file you can do something like this

int i = 0;

while (fgets(line, 1000, textfile)) { 
 
       i  ;

       if (i == n) {
           // do stuff with nth line
           break;
       }
}

This approach uses a counter to count until the nth iteration is reached. Once it is, you can do what you need to do with the nth line.

Also this may be unrelated but you should never use printf without a format specifier as you have in printf(line);. This can be dangerous and could be used by an attacker to exploit the program. I would recommend that in your case puts(line); is a better alternative.

CodePudding user response:

For example:

int readNthLine(FILE *fi, char *buff, size_t buffsize, size_t line)
{
    fseek(fi, 0, SEEK_SET);
    {
        for(size_t cline = 0; cline < line; cline  )
        {
            if(!fgets(buff, buffsize, fi)) return -1;
        }
    }
    return 0;
}

This very simple function will work only if the size of the buffer is larger than the length of the longest line in the file.

Of course, you should check the result of any I/O operation.

  •  Tags:  
  • c
  • Related