如何编写一个c程序来创建文件?

时间:2019-04-24 17:26:06

标签: c file structure

我想通过从用户导入文件名来创建文件,请帮助

int file_name;
printf("Enter ID NUMBER : ");
scanf("%d",&file_name);
FILE *fin;
fin = fopen(&file_name , "w");

1 个答案:

答案 0 :(得分:2)

这里

FILE *fin;
fin = fopen(&file_name , "w"); /* this is wrong, since &file_name is of int* type */

fopen()期望使用char*类型的第一个参数,但是您提供了int*类型的参数,这是错误的,并且编译器已正确报告为

  

错误:不兼容的指针类型传递         'int *'到类型'const char *'的参数         [-Wincompatible-pointer-types]

如果可以使用如下标记进行编译 -Wall -Wpedantic -Werror。在fopen()的手册页中

  

FILE * fopen(const char * pathname,const char * mode);

file_name声明为字符数组 ,并将文件名存储到其中。

char file_name[1024]; /* take a char array to store file name */
/* @TODO : store actual file name into file_name array */
FILE *fin = fopen(file_name , "w");
if(fin == NULL) {
  /* @TODO : error handling */
}