大佬们,帮我看看这个程序为什么会出现段错误

coverlo 2017-09-05 10:28:20
[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;
}
...全文
95 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
coverlo 2017-09-05
  • 打赏
  • 举报
回复
引用 2 楼 paschen 的回复:
pfile = (FILE*)filename; if (!fopen(pfile, "w")) 改成: pfile = fopen(filename, "w") if (!pfile)
不好意思,点错了。 我明白了,谢谢
paschen 2017-09-05
  • 打赏
  • 举报
回复
pfile = (FILE*)filename; if (!fopen(pfile, "w")) 改成: pfile = fopen(filename, "w") if (!pfile)
coverlo 2017-09-05
  • 打赏
  • 举报
回复

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧