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

问题描述 投票:0回答:1

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

int file_name;
printf("Enter ID NUMBER : ");
scanf("%d",&file_name);
FILE *fin;
fin = fopen(&file_name , "w");
c file structure
1个回答
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 */
}
© www.soinside.com 2019 - 2024. All rights reserved.