0
#include "stdio.h" 

main( ) { 
    FILE *fp1; 
    char oneword[100]; 
    char *c;       

    fp1 = fopen("TENLINES.TXT","r"); 
    do { 
        c = fgets(oneword, 100 ,fp1); /* get one line from the file */ 
        if (c != NULL) 
        printf("%s", oneword); /* display it on the monitor */ 
    }  while (c != NULL); /* repeat until NULL */ 

    fclose(fp1); 
} 

I don't understand why this code need to have a char *c. What does the char *c do here. I tried to change all the 'c' to 'oneword' but it would always have an error. Can you please explain this? Thanks.

dragosht
  • 3,237
  • 2
  • 23
  • 32

4 Answers4

2

Did you read the documentation of fgets(3)? It returns NULL on failure (e.g. when you reached the end of file).

And of course you should check against failure of fopen(3) like:

fp1 = fopen("TENLINES.TXT","r"); 
if (!fp1) 
  { perror("fopen TENLINES.TXT failure"); exit(EXIT_FAILURE); };

Then compile with all warnings & debug info (e.g. gcc -Wall -Wextra -g) and learn how to use the debugger (gdb)

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

fgets() returns a pointer. Where do you want to store it? There should be a pointer defined for this purpose. That's why char *c is declared. Also you can't use oneword for this, that's already used for storing the line read from file.

doubleE
  • 1,027
  • 1
  • 12
  • 32
1

[too long for a comment]

Using a while-loop instead of a do-loop would allow you to get around without defining c:

#include <stdlib.h>
#include <stdio.h>

int main(void) 
{ 
  int result = EXIT_SUCCESS; /* Be optimistic! */

  FILE * fp1 = fopen("TENLINES.TXT", "r"); 
  if (NULL == fp1)
  {
    result = EXIT_FAILURE; 
    perror("fopen() failed");
  }
  else
  {
    char oneline_if_shorter_then_100_characters[100]; 
    while (NULL != fgets(oneline_if_shorter_then_100_characters, sizeof oneline_if_shorter_then_100_characters, fp1)) /* get one line from the file */ 
    {
      printf("%s", oneline_if_shorter_then_100_characters); /* display it on the monitor */ 
    } /* repeat until fgets had returned NULL */ 

    fclose(fp1); 
  }

  return result;
}
alk
  • 69,737
  • 10
  • 105
  • 255
0

A little bit safer way to handle your requirement using fgetc()

#include <stdio.h>

int main() { 
FILE *fp1; 
char oneword[100]; 
int c;

int i=0;

if((fp1 = fopen("Newfile.x","r")) <= 0){
    return 1; // File opening failled
}  

  while((c=fgetc(fp1))!=EOF){
      oneword[i]=c;
      i++;

      if(i>=99 || c=='\n'){
            // We are out of buffer OR new line reached
            oneword[i]='\0';
            printf("%s \n",oneword);
            i=0;
      }
   }

    // If some left ; output that too
    oneword[i]='\0';
    printf("%s \n",oneword);

  return 1;
}
Kavindu Dodanduwa
  • 12,193
  • 3
  • 33
  • 46