我正在研究一个应该读取文件的函数,我需要将文本文件的第一行转换为整数。该函数将文件作为参数,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 的新手。所以,我将不胜感激任何帮助。谢谢
如果你仔细查看函数的描述
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
可以读取一个空字符串。