You are here:

C/error reading text file

Advertisement


Question
Again a big problem for me but a flick of fingers for you. Here is the simple high level file IO
c code:

/*a program similar to cat*/
#include "stdio.h"
main()
{
FILE *fp;
char path[]="\0", ch;
printf("Enter the name of file you wish to open: ");
scanf("%s",&path);
fp = fopen(path,"r");
if (fp == NULL )
{
 printf("\nThe specified can't be opened");
 exit(0);
}
printf("%c",fgetc(fp));
while( (ch = fgetc(fp)) != EOF)
{
 putchar(ch);
}
fclose(fp);        /*removal*/
}

The maniac here is every thing is fine but after giving the required output the error "Segmentation Fault" persists. The system is Linux version 2.6.12 (root@Knoppix) (gcc-Version 3.3.6 (Debian 1:3.3.6-7)) #2 SMP.

I tried to run the same program in Winxp using Dev-C++ IDE and the results were exactly same.


Answer
I compiled and executed your program on Sun-Solaris and it didn't crash. It printed the contents of the file on the screen.

Any way, after looking at your code, I think you have to make few corrections. Here is the corrected code. Please do try and let me know its results:
#include "stdio.h"

main()
{
   FILE *fp;
   char path[128]="\0", ch;

   printf("Enter the name of file you wish to open: ");
   scanf("%s", path);

   fp = fopen(path,"r");
   if (fp == NULL )
   {
       printf("\nThe specified can't be opened");
       exit(0);
   }

   printf("%c",fgetc(fp));
   while( (ch = fgetc(fp)) != EOF)
   {
       putchar(ch);
   }
   fclose(fp);        /*removal*/
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.