大佬们,帮我看看这个程序为什么会出现段错误
[code=c]//Program 12.1 writing a file a character at a time
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define LENGTH 81 //Maximum input length
int main(void)
{
char mystr[LENGTH]; //Input string
int mychar = 0; //Character for output
FILE* pfile = NULL; //File pointer
char* filename = "myfile.txt";
printf("Enter an interesting string of up to %d characters:\n", LENGTH-1);
if( !fgets(mystr, LENGTH, stdin) ) //Read in a string
{
printf("Input from keyboard failed.\n");
exit(1);
}
//Create a new file we can write
pfile = (FILE*)filename;
if( !fopen(pfile, "w") )
{
printf("Error opening %s for writing. Program terminated.\n", filename);
exit(1);
}
setvbuf(pfile, NULL, _IOFBF, BUFSIZ);
for( int i = strnlen(mystr, LENGTH)-1; i>=0; --i )
fputc(mystr[i],pfile); //Write string to file backward
fclose(pfile); //Close the file
//Open the file for reading
if( !fopen( pfile, "r" ) )
{
printf("Error opening %s for reading. Program terminated.", filename);
exit(1);
}
setvbuf(pfile, NULL, _IOFBF, BUFSIZ);
//Read a character from the file and display it
printf("the data read from the file is:\n");
while( (( mychar = fgetc(pfile) )!= EOF) )
putchar(mychar); //Output character from tht file
putchar('\n'); //Write newline
fclose(pfile); //Close the file
pfile = NULL;
remove(filename); //Delete the physical file
return 0;
}