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

时间:2015-01-19 13:39:41

标签: c fgets scanf

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

问题是fgets似乎在cotefgets返回5之前​​将其正在读取的字符串添加到strlen(o.cote),然后它返回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] = '\0';

    // 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如何影响前一个变量以及如何阻止它?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

欢迎来到c-strings的世界。假设cote应该是5个字符长,你实际上需要保留6个字符,以便为字符串字符的结尾留出空间(&#39; \ 0&#39;);发生了什么事,fscanf写了这个字符串作为titre的第一个字符,然后fgets覆盖了那个,这就是为什么你看到你所看到的。还要注意,就我而言,scanf和相关是魔鬼的工具;为什么不只是使用fgets(它允许你指定读取的最大字节数[仔细阅读联机帮助页以避免一个关闭])?