int save(int *file,int K)
{
int i;
char *name;
FILE *fp;
name=(char *)malloc(256);
puts("type file name\n");
getchar();
fgets(name,256,stdin);
if((fp=fopen(name,"w"))==NULL)
{
puts("file can't be opened\n");
return 0;
}
fprintf(fp,"%d\n",K);
for(i=0; i<K; i++)
{
fprintf(fp,"%d\n",*(file+i));
}
fclose(fp);
return 1;
}
为什么这不起作用,但当我使用
fopen("text.txt","w")
时,一切正常?我该怎么解决? 最佳答案
这是因为fgets
将换行符'\n'
附加到字符串。你得先把这个剪掉。
if (isspace(name[strlen(name)-1]))
name[strlen(name)-1] = '\0';
关于c - 当我使用char数组作为文件名时,fopen始终返回NULL,但是如果我使用“file.txt”之类的名称,一切正常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22355346/