0

So the problem is, im trying using fgets to read a line from a text and print it out, and it just doesn't work quite well, its read all the file perfectly until the end,but it reads the last line twice and than "shouts" segemnation fault.

void somefun(FILE *file){
char *buf[81];

    while(!feof(file)){
        if(fgets(buf,80,file)){
        continue;}
       printf("%s,buf); }

void main() {
FILE *fp;
fp=fopen("somefile.txt","r+");
somefun(fp); }
Zi Elad
  • 1
  • 1
  • Use `feof()` for checking whether your read failed due to EOF, not to see if there is more data left. It indicates whether you've tried to access past the end, not whether you're at the end. – Dmitri Aug 03 '19 at 00:39
  • 1
    Also, you've declared `buf` to be an array of 81 `char *`, not an array of 81 `char`. And you're missing a quotation mark. – Dmitri Aug 03 '19 at 00:48
  • 1
    When `fgets()` encounters end of file, the content of `buf` is indeterminate, so printing it causes undefined behaviour. Change the loop condition so it is based on the return value of `fgets()` (only print if `fgets()` does not indicate an error) and discard the usage of `feof()`. And `main()` returns `int`, not `void`. – Peter Aug 03 '19 at 00:49
  • The logic in this function is just plain odd. Besides the improper use of `!feof` as a condition, and assuming you actually fix the type of `buf`, you seem to be purposely wanting to ignore all lines that are read successfully by way of that `if` test condition and subsequent `continue` So, what did you actually want this code to do? If the intent was as you said *"to read **a** line"* the loop isn't even needed *at all*. – WhozCraig Aug 03 '19 at 07:58
  • Try: `while(fgets(buf,80,file)) printf("%s",buf);` – Sir Jo Black Aug 03 '19 at 10:38

1 Answers1

0

There is no need to use feof() at all.

It could look like this:

#include <stdio.h>

void somefun(FILE* file) {
  char buf[80]; 

  while (NULL != fgets(buf, 80, file)) {
    printf("%s", buf);
  }

  if (ferror(file)) {
    fprintf(stderr, "fgets() failed\n");
  }
}

int main(void) {
  FILE *fp = fopen("somefile.txt", "r+");
  if (NULL == fp) {
    fprintf(stderr, "fopen() failed\n");
  }
  else {
    somefun(fp); 
  }
}
alk
  • 69,737
  • 10
  • 105
  • 255