1

I have a buffer and I want to read a pascal file and put content in the buffer. Then I want to add '$' sign in the end of buffer. When I tried to do it i get only the last row from my pascal file into buffer I don't why. please help. Here is my code!

FILE *fp = fopen("test.pas", "r");
while(!feof(fp)){
   fscanf(fp, "%s", buffer);
   }
   strcat(buffer,"$"); fclose(fp);
  • 2
    At first glance: related: [c - Why is “while ( !feof (file) )” always wrong? - Stack Overflow](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – MikeCAT May 04 '20 at 12:31
  • What do you want to do? Read the whole file into `buffer`? – MikeCAT May 04 '20 at 12:36
  • 1
    Apart from `while (!feof(fp))` which is wrong, you are overwriting the buffer every single time with the new line you read. Also, using `%s` is always wrong. Don't! You might want to use `getline` (GNU extension) or `fgets` specifying a maximum length. – Marco Bonelli May 04 '20 at 12:38

1 Answers1

0

You are reading the lines, the problem is that you are overwriting them over and over again in your buffer, so only the last one stays.

A good way to do this is to use fscanf in the while condition, this way you'll have a sound stop condition and you can verify the read results, which should allways be done.

You can do something like this:

Live demo

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINES 100 //nr of lines

int main() {
    //array of 100 pointers to char, so 100 lines max, adapt it to you needs
    //should be the equal or larger than the max number of lines to be read
    char *buffer[LINES]; 
    FILE *fp;
    int i = 0;

    //checking the opened file is also a good practice
    if (!(fp = fopen("test.pas", "r"))) { 
        perror("Not able to open file!");
        return 1;
    }
    do {
        if (!(buffer[i] = malloc(100))) { //allocate memory for each line        
            perror("Memory allocation failed"); //checking memory allocation
            return 1;
        }
    }while (fscanf(fp, "%99s", buffer[i]) == 1 && strcat(buffer[i], "$") && i++ < LINES - 1);
    buffer[i] = NULL; // sentinel, marks the end of the array of strings

    i = 0; //reset i
    while (buffer[i]) {
        puts(buffer[i]); //print each line
        free(buffer[i]); //free memory
        i++;
    }
    fclose(fp);
}

Note that fscanf() reads until the next blank space, so for strings with more than 1 word you should use something like fgets or you if you use UNIX, getline().

feof is not the best option as you can see in Why is “while ( !feof (file) )” always wrong?

The standard actually exemplifies the correct usage of feof ISO/IEC9899:2017 N2176 § 7.21.6.2 - 19

anastaciu
  • 23,467
  • 7
  • 28
  • 53