我仍然被认为是c语言的初学者,我开始学习文件。我已经建立了一个空白文件。每次我编译这个程序,文件还是空白的。需要帮助!!
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * x;
char name[25];
printf("enter your name: ");
scanf("%s", &name);
x = fopen("x1.txt", "w");
if(x = NULL)
{
printf("Unable to open the file");
}
else
{
fprintf(x, "%s\n", name);
printf("date has been entered successfully to the file");
fclose(x);
}
return 0;
}
谢谢你
最佳答案
一个文件存在,并包含我的名字,在作出以下变化和重建/运行程序:
(原因见第行注释)
更改:
if(x = NULL)//assignment - as is, this statement will always evaluate
//to false, as x is assigned to NULL.
致:
if(x == NULL)// comparison - this will test whether x is equal to NULL without changing x.
更改:(这是未填充文件的密钥)
scanf("%s", &name);//the 'address of' operator: '&' is not needed here.
//The symbol 'name' is an array of char, and is
//located at the address of the first element of the array.
致:
scanf("%s", name);//with '&' removed.
或者更好:
scanf("%24s", name);//'24' will prevent buffer overflows
//and guarantee room for NULL termination.
还有一种方法来处理关于not using scanf at all...的评论:
char buffer[25];//create an additional buffer
...
memset(name, 0, 25);//useful in loops (when used) to ensure clean buffers
memset(buffer, 0, 25);
fgets(buffer, 24, stdin);//replace scanf with fgets...
sscanf(buffer, "%24s", name);//..., then analyze input using sscanf
//and its expansive list of format specifiers
//to handle a wide variety of user input.
//In this example, '24' is used to guard
//against buffer overflow.
关于最后一种方法,这里有一页detailing the versatility使用sscanf处理用户输入字符串。
关于c - 程式无法运作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42866761/