gpt4 book ai didi

c - 包含 fscanf 的程序无法编译

转载 作者:行者123 更新时间:2023-11-30 21:12:37 25 4
gpt4 key购买 nike

作为一个 C 语言新手,我仍在努力理解大量的函数。

其中一个特别给我带来了很多问题。我正在尝试使用 fscanf 但我不断收到一个奇怪的错误:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
FILE *dict = fopen(argv[1], "r");

// skim through every word in a dictionary
while (fscanf(dict, "%s", word) != EOF)
{
// iterate through every chracter in the word
for (int i = 0, int j = strlen(word); i < j; i++)
{
printf("%c", word[i]);
}
printf("\n");
}

return 1;
}

我正在尝试创建一个循环,浏览文件中的每个单词,该文件只是一系列单词。我假设我编写的代码就是这样做的,将每个单词存储在名为 "word" 的字符串中。不幸的是,我不断收到此错误:

error: format specifies type 'char *' but the argument has type 
'<dependent type>' [-Werror,-Wformat]
error: use of undeclared identifier 'word'

即使我尝试初始化 char * 变量 "word",也会不断弹出一些其他错误。也许我不完全理解 fscanf 的工作原理,有人可以提供一些许可吗?

如何让上面的程序编译?

最佳答案

因为您使用的是 C,所以这个答案并不关心臭名昭著的“缓冲区溢出错误”,但请记住这一点。在使用“fscanf”之前,您需要声明“word”变量。看起来像...

const size_t MAX_WORD_LEN=256; 
char word[MAX_WORD_LEN];

那么,你可以。

while (fscanf(file, "%s", word) != EOF)
{
}

此处,最大“单词”长度为 255 个字符(不以 NULL 字符结尾)。因此,在您的文件中,单个单词的长度不能超过 255 个字符(在大多数情况下,应该没问题)。整个程序很可能如下:

#include <stdio.h>


const char* const usage_msg = "Usage: program_name input-file\nInput file contains words in English or some languages. \n";
const char* const fopen_err = "\nUnable to open file: ";
const size_t MAX_WORD_LEN = 256;

int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "%s", usage_msg);
return -1;
}
else {
/* if argv[1] contains something that is not supposed to be, it will be infamous buffer overflow. */
/* any validation on argv[1] is welcomed here */
FILE *pf = fopen(argv[1], "r");
char word[MAX_WORD_LEN];
if (pf == NULL) {
fprintf(stderr, "%s%s", fopen_err, argv[1]);
return -2;
}
/* overflow can be avoided by specifying width 255 to %s */
while (fscanf(pf, "%255s", word) != EOF) {
printf("%s\n", word);
}
}
return 0;
}

关于c - 包含 fscanf 的程序无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45278130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com