[英]Program isnt working
我还是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.
还有一种方法可以解决有关根本不使用scanf的评论... :
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.