-3

I'm experiencing a problem in the resolution of an exercise. I need to read N strings from file, but I can only read the first. How can I fix it?

#include <stdio.h>    

int main() {

 /* variable declarations */

   FILE *fp;
   char vet[100];


   fp = fopen("file.txt","r");  /* open file with N strings */

   while(!feof(fp)) {
     fgets(vet, 100, fp);
     vet[100]='\0';
     printf("%s\n", vet);  
   }

}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 3
    `char vet[100];` then `vet[100]='\0';` <-- Boom ! (arrays indexes start at 0) – Cid Mar 28 '19 at 13:59
  • 3
    Also you should make sure to call `fclose` when you're done with the file. – Evan M Mar 28 '19 at 14:05
  • 4
    [Why is “while (!feof(file))” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) – Lundin Mar 28 '19 at 14:13

1 Answers1

2

vet[100]='\0' this will generate error in runtime, also you don't need this line of code because fgets will handle the end of the string itself.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Ismail
  • 2,322
  • 1
  • 12
  • 26
  • It's true! It woooork now! Thank's a lot! – simone golino Mar 28 '19 at 14:02
  • 1
    @simonegolino you still may need to handle the `\n` that `fgets` adds at the end of the string. – Jabberwocky Mar 28 '19 at 14:29
  • 1
    @simonegolino _"this will generate error in runtime"_, no this statement is wrong. It triggers _undefined behaviour_ which is roughly anything between "program crashes instantly" and "apparently working fine". – Jabberwocky Mar 28 '19 at 14:30