在C中传递fopen()的参数问题

oknrviil  于 2023-03-12  发布在  其他
关注(0)|答案(1)|浏览(89)

我正在编写一个函数,它应该读取一个文件,我需要把文本文件的第一行转换成一个整数,这个函数把文件作为一个参数char *filename。
但是,打开文件时出现错误。
错误如下所示:“传递'fopen'的2的参数使指针来自整数,而没有强制转换[-Wint-conversion] gcc”

FILE *fp = fopen(filename, 'r'); //Line with error

 char str[6]; //since the first line is a 5 digit number
 fgets(str, 6, fp);
 sscanf(str, "%d", *number); //number is the pointer I'm supposed to save this value to, it is also a parameter for the function

我刚到C.所以,我会很感激任何帮助.谢谢

6rvt4ljy

6rvt4ljy1#

如果仔细查看函数fopen的描述,您会发现它声明为

FILE *fopen(const char * restrict filename, const char * restrict mode);

也就是说,两个参数都具有指针类型const char *
因此,您需要使用字符串常量"r",而不是整数字符常量'r'作为第二个参数

FILE *fp = fopen(filename, "r");

你还得写

sscanf(str, "%d", &number);

代替

sscanf(str, "%d", *number);

如果number的类型是int,或者如果它的类型是int *,那么你需要写

sscanf(str, "%d", number);

并且期望声明字符数组具有至少7个字符,以允许还读取记录的新行字符'\n'

char str[7]; //since the first line is a 5 digit number
 fgets(str, sizeof( str ), fp);

否则,fgets的下一次调用可能读取空字符串。

相关问题