程序不起作用

时间:2017-03-17 20:43:04

标签: c file

我仍然被认为是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;
}

谢谢

1 个答案:

答案 0 :(得分:5)

在进行以下更改并重建/运行程序后,文件已存在且包含我的名字:

(见原因评论)
变化:

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.

关于最后一个方法,这里是使用sscanf处理用户输入字符串的页面 detailing the versatility

相关问题