fgets 将字符串添加到另一个变量

fgets adding string to another variable

我正在尝试用 C 语言做一个相对简单的库项目,但我被卡住了。我正在使用 fscanf 设置一个变量(cote 是 char[5])然后 fgets 设置另一个变量(titre 这是一个 char[50] ).这两个变量都属于一个名为 Ouvrage 的结构。

问题是 fgets 似乎在 fgets 之前将它正在读取的字符串添加到 cote : strlen(o.cote) returns 5 之后它 returns 31.

这是 test.c 的代码:

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

typedef struct {
    char cote[5];
    char titre[50];
} Ouvrage;

void main(void)
{
    FILE *flot;
    Ouvrage o;

    // Opening the file

    flot = fopen("ouvrages.don", "r");

    if(flot == NULL)
    {
        printf("Error opening file.\n");
        exit(1);
    }

    // Reading the cote

    fscanf(flot, "%s%*c", o.cote);

    // Printing the length of cote

    printf("STRLEN: %d\t", strlen(o.cote));

    // Reading the titre

    fgets(o.titre, 50, flot);
    o.titre[strlen(o.titre) - 1] = '[=10=]';

    // Printing the length of cote again.... Different.

    printf("STRLEN: %d\n", strlen(o.cote));
}

这是 ouvrage.don 文件:

NJDUI
Charlie et la chocolaterie
ROM
Rhoal Doal

那么 fgets 如何影响先前的变量以及如何停止它?非常感谢任何帮助。

欢迎来到 C 字符串的世界。假设 cote 应该是 5 个字符长,你实际上需要保留 6 个字符,以便 space 作为字符串字符的结尾('\0');发生的事情是 fscanf 将该字符串字符写为 titre 的第一个字符,但随后 fgets 覆盖了它,这就是为什么你看到了你所看到的。还要注意,就我而言,scanf 和相关是魔鬼的工具;为什么不只使用 fgets(它允许您指定要读取的最大字节数 [仔细阅读联机帮助页以避免偏移一个])进行两次读取?