我正在编写一个函数,它应该读取一个文件,我需要把文本文件的第一行转换成一个整数,这个函数把文件作为一个参数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.所以,我会很感激任何帮助.谢谢
1条答案
按热度按时间6rvt4ljy1#
如果仔细查看函数
fopen
的描述,您会发现它声明为也就是说,两个参数都具有指针类型
const char *
。因此,您需要使用字符串常量
"r"
,而不是整数字符常量'r'
作为第二个参数你还得写
代替
如果
number
的类型是int
,或者如果它的类型是int *
,那么你需要写并且期望声明字符数组具有至少
7
个字符,以允许还读取记录的新行字符'\n'
否则,
fgets
的下一次调用可能读取空字符串。