无法写入文件
unable to write into file
这是将内容写入文件的代码。
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
FILE *fp;
char ch(90);
fp = fopen("books.txt","w");
if(fp == NULL)
{
puts("Cannot open file");
}
printf("Enter lines of text:");
while(strlen(gets(ch)) > 0)
{
fputs(ch, fp);
}
fclose(fp);
}
我遇到了 4 个错误。它们是:
- Cannot convert
int
to char *
in function main()
.
- Type mismatch in parameter
__s
in call to gets(char *)
in function main()
.
- Cannot convert
int
to const char *
in function main()
.
- Type mismatch in parameter
__s
in call to fputs(const char *,FILE *)
in function main()
.
我认为你对 char 数组的定义是错误的:
char ch(90);
必须
char ch[90];
在你的代码中
char ch(90);
被视为函数声明,这不是你想要的。您需要使用 []
运算符来表示数组,例如
char ch[90]; //array named ch having 90 chars
之后,如果 if(fp == NULL)
成功(即文件打开失败),仅打印一条消息 不 就足够了。您不应在程序的任何地方进一步使用返回的 fp
,即,您必须跳过所有涉及该 fp
的语句。否则,使用 无效 文件指针将导致 undefined behaviour.
也就是说,
- 永远不要使用
gets()
,而是使用 fgets()
。
main()
的正确签名是 int main(void)
。
首先:
你的字符数组定义应该是:
char ch[90];
其次:
您对 main
的定义应该是:
int main(void)
第三:
考虑使用 fgets()
而不是 gets()
。
检查字符数组定义,
应该是 char ch[90];
这是将内容写入文件的代码。
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
FILE *fp;
char ch(90);
fp = fopen("books.txt","w");
if(fp == NULL)
{
puts("Cannot open file");
}
printf("Enter lines of text:");
while(strlen(gets(ch)) > 0)
{
fputs(ch, fp);
}
fclose(fp);
}
我遇到了 4 个错误。它们是:
- Cannot convert
int
tochar *
in functionmain()
.- Type mismatch in parameter
__s
in call togets(char *)
in functionmain()
.- Cannot convert
int
toconst char *
in functionmain()
.- Type mismatch in parameter
__s
in call tofputs(const char *,FILE *)
in functionmain()
.
我认为你对 char 数组的定义是错误的:
char ch(90);
必须
char ch[90];
在你的代码中
char ch(90);
被视为函数声明,这不是你想要的。您需要使用 []
运算符来表示数组,例如
char ch[90]; //array named ch having 90 chars
之后,如果 if(fp == NULL)
成功(即文件打开失败),仅打印一条消息 不 就足够了。您不应在程序的任何地方进一步使用返回的 fp
,即,您必须跳过所有涉及该 fp
的语句。否则,使用 无效 文件指针将导致 undefined behaviour.
也就是说,
- 永远不要使用
gets()
,而是使用fgets()
。 main()
的正确签名是int main(void)
。
首先:
你的字符数组定义应该是:
char ch[90];
其次:
您对 main
的定义应该是:
int main(void)
第三:
考虑使用 fgets()
而不是 gets()
。
检查字符数组定义,
应该是 char ch[90];