【问题标题】:fseek and fgets in C programming not used correctly here?C 编程中的 fseek 和 fgets 在这里没有正确使用?
【发布时间】:2017-05-15 00:14:11
【问题描述】:
char * file = malloc(buffer);
assert(file != 0);
char str[20];

snprintf(file, buffer, "%s/%s", newestDirName, fileInDir->d_name);
FILE * input = fopen(file, "r"); // read
fseek(input, 0, SEEK_END);
fgets(str, 20, input);
printf("str = %s \n", str);

我正在读取的文件有最后一行:

ROOM TYPE: END_ROOM

为什么 str 不存储“ROOM TYPE: END_ROOM

我认为fseek(input, 0, SEEK_END) 获取最后一行,光标从最后一行的最左侧位置开始。这是错的吗?

我认为fgets(str, 20, input) 从输入中获取 20 个字符并将其放入 str 中,这是一个 char * 变量。

但是当我打印 str 时,我对 str 的值产生了乱码:

str = ▒▒As=   

【问题讨论】:

  • 你认为在你一直寻找到end之后会从文件中next读取什么?
  • 你搜索到文件末尾; fgets() 文件结束后没有任何内容可供读取。它不会寻找到文件末尾之前的最后一行的开头。请注意,fgets(str, 20, input) 最多读取 19 个字符,并在最后一个字符之后放置一个空字节。如果换行符出现在第 19 个字符之前,它可能会读取少于 19 个字符,并将空字节添加到第 20 个位置。您应该始终测试输入函数的返回值——fgets() 的返回值将是 NULL,表示 EOF。在 EOF 上,字符串未设置为任何确定的值。

标签: c file printf fgets fseek


【解决方案1】:

如果你需要使用fgets,你可以试试这个。但是,没有什么能保证一行中的字符数不超过20个字符,特别是如果每​​行的字符数是可变的。

char str[20]={0};
FILE * input = fopen("file.txt", "r"); // read
if(input)
{
    char *ptr;/*Warns you if you have reached the end of the file or some error*/
    do 
    {   
        ptr=fgets(str, 20, input);
    } while(ptr);
    if(str)
        printf("str = %s \n", str);
    fclose(input);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    相关资源
    最近更新 更多