Skip to content
Advertisement

How to read some specific lines in a file, and print them in console in Linux C programming

I write two new lines in a file. The new lines are appended to this file. How can print these two new lines to the console.

Could you please give me some examples about this?

The process is below:

  1. fd = open(file , O_WRONLY | O_APPEND, 0666);
  2. ret = read(0, buf, 100);
  3. write(file, buf, strlen(buf));

  4. The problem is 4th process. How can I read the new line which is written in file just now, rather than old contents in this file. Below is my code to print the whole contents.

    FILE *fptr;
    char chr;
    fptr = fopen(file, "r");
    if (fptr == NULL)
    {
        perror("open");
        exit(1);
    }
    chr = fgetc(fptr);
    while(chr != EOF) {
        printf("%c", chr);
        chr = fgetc(fptr);
    }
    clearerr (fptr);
    fclose(fptr);
    

Advertisement

Answer

if you want to read back the data you just wrote then you can use ftell to get your position in the file then write, then fseek to reposition to the same point and read

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement