C - fgets() 产生乱码

标签 c malloc fgets

我使用 VS 2010 作为我的 IDE,这段代码工作正常,直到 fgets 被作为 puts 参数调用的那一行。它可以很好地记录文件中的数字,但也会打印一些烦人的乱码。也许我在某个地方缺少一个\0 ,不知道。其他人在 mingw 或 gcc 等其他编译器上尝试过,效果很好。

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

int main()
{
    int *a, n, i;
    char str[512];
    FILE *f;
    printf("Insert array size: ");
    scanf("%d", &n);
    if(n <= 0)
    {
        printf("%d is not an allowed value!\n", n);
        return 1;
    }
    a = (int*)malloc(n * sizeof(int));
    if(a == NULL)
        return 2;
    putchar('\n');
    f = fopen("myarray.txt", "r+");
    if(f == NULL)
        return 3;
    for(i = 0; i < n; ++i)
    {
        printf("Insert %d. element of the array: ", i + 1);
        scanf("%d", &a[i]);
        fprintf(f, "%d ", a[i]);
    }
    putchar('\n');
    puts(fgets(str, 512, f));
    free(a);
    fclose(f);
    return 0;
}

最佳答案

在代码中调用 fgets 的地方,文件指针应该位于文件末尾。

因此,fgets应该返回 NULL 指针,因为它在读取任何字符之前就到达了 EOF。

因此,您将 NULL 指针传递给 puts .

关于C - fgets() 产生乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13998734/

相关文章:

c - 使用 sscanf 和 fgets 读取多行文本文件

php - 将 txt 文件的每一行读取到新的数组元素

C strncat 不工作并引发访问冲突

c - 传递一个指向数组的指针

c - 为什么clone创建的线程中无法正确调用malloc/free接口(interface)?

c - 我正在尝试释放结构数组但得到 free() : invalid next size (fast): 0x0000000000afa010

c - 读取用户输入时 fgets 段错误

c++ - 如何在 MFC 对话框按钮上设置管理权限图标?

c - 指定 RIDEV_NOLEGACY 时,Win32 原始输入会阻止输入区域设置切换

C段错误