C - Reading from a file

76 views Asked by At

I have a text file containing the following:

ANT. Small insect,  
sometimes has wings on its back.

BEAR. Large beast.

I have a c program:

int main(void)
{
   FILE *fp;
   int c;

   fp = fopen("myfile.txt","r");
   if(fp == NULL) 
   {
      perror("Error in opening file");
      return(-1);
   } do {
      c = fgetc(fp);
      if(feof(fp))
         break ;
    if (c != '\n')
        printf("%c", c);
   }while(1);

   fclose(fp);
}

However it only prints:

BEAR. Large beast.

I want it to print:

ANT. Small insect, sometimes has wings on its back.  
BEAR. Large beast.
2

There are 2 answers

1
rabi shaw On BEST ANSWER
/*Everything looks find in your code. in my machine it is working fine . I have only added a if condition to print the contents same as the file thats it .. */

#include<stdio.h>

int main(void)
{
   FILE *fp;
   int c;

   fp = fopen("rabi.txt","r");
   if(fp == NULL)
   {
      perror("Error in opening file");
      return(-1);
   } do {
      c = fgetc(fp);
      if(feof(fp))
         break ;

        printf("%c", c);

        printf ("\n");
   }while(1);
printf ("\n");
   fclose(fp);
}


o/p-->
rabi@rabi-VirtualBox:~/rabi/c$ gcc 11.c 
rabi@rabi-VirtualBox:~/rabi/c$ ./a.out 
ANT. Small insect,
sometimes has wings on its back.

BEAR. Large beast.
0
Sourav Kanta On

Text files created on DOS/Windows machines have different line endings than files created on Unix/Linux. DOS uses carriage return and line feed ("\r\n") as a line ending, which Unix uses just line feed ("\n"). You need to be careful about transferring files between Windows machines and Unix machines to make sure the line endings are translated properly.

Read More