C/error reading text file
Expert: Narendra - 6/23/2006
QuestionAgain 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.
AnswerI 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*/
}