【发布时间】:2015-01-19 13:39:41
【问题描述】:
我正在尝试用 C 语言做一个相对简单的库项目,但我被卡住了。我使用fscanf 设置一个变量(cote 是char[5]),然后fgets 设置另一个变量(titre 这是一个char[50])。这两个变量都属于一个名为Ouvrage 的结构。
问题是fgets 似乎将它正在读取的字符串添加到cote,在fgets 之前:strlen(o.cote) 返回 5,但之后它返回 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 如何影响先前的变量以及如何阻止它?非常感谢任何帮助。
【问题讨论】: