【问题标题】:Passing argument for fopen() in C issues在 C 问题中为 fopen() 传递参数
【发布时间】:2023-02-25 04:19:12
【问题描述】:

我正在研究一个应该读取文件的函数,我需要将文本文件的第一行转换为整数。该函数将文件作为参数,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 的新手。所以,我将不胜感激任何帮助。谢谢

【问题讨论】:

  • 你写了 ' 而不是 "
  • 我尝试将其更改为“,但仍然出现错误。
  • @shari 什么错误? fopen(filename, "r") 应该有效,假设 filename 有效。 (一般来说,“错误”几乎是对任何错误最无用的描述。我们需要查看消息和导致它的代码。)我希望你的 sscanf 调用出现错误,正如 Vlad 的回答所提到的.

标签: c compiler-errors scanf fopen fgets


【解决方案1】:

如果您仔细查看函数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 个字符,以允许还读取记录的换行符 ' '

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 2013-03-21
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    相关资源
    最近更新 更多