包含fscanf的程序无法编译

时间:2017-07-24 10:25:17

标签: c scanf

作为一个对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如何运作,是否有人可以提供一些许可?

如何编译上述程序?

1 个答案:

答案 0 :(得分:-1)

因为您使用的是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;
}
相关问题