c - 在 C 中,如何将文本文件的不同行保存到不同的变量中

标签 c file file-io

如何将文本文件中的不同行保存到不同数据类型的不同变量中;所有这些变量构成一个结构(在我的示例中是一个具有以下内容的飞行结构)。

struct Flight
{
     int flightNum;
     char desination[30];
     char departDay[15];
};

我想通过文本文件添加的信息示例是。

111
NYC
Monday

我显然想将单词 NYC 和 Monday 保存到一个字符数组中,但我想将 111 保存到一个整数变量中

目前为止

while (fscanf(flightInfo, "%s", tempName) != EOF)
{
     fscanf(flightInfo, "%d\n", &tempNum);
     flight.flightNumber = tempNum;
     fscanf(flightInfo, "%s\n", tempName);
     strcpy(flight.desination, tempName);
     fscanf(flightInfo, "%s\n", tempName)
     strcpy(flight.departDay, tempName);
}

假设flightInfo是一个指向文件名的指针,tempNum是一个整数,tempName是一个字符数组

最佳答案

听起来您的方向是正确的。

像这样的事情怎么样:

#define MAX_FLIGHTS 100
...
struct Flight flights[MAX_FLIGHTS ];
int n_flights = 0;
...
while (!feof(fp) && (n_flights < MAX_FLIGHTS-1))
{
     if (fscanf(fp, "%d\n", &flights[n_flights].flightNum) != 1)
        error_handler();
     if (fscanf(fp, "%29s\n", flights[n_flights].destination) != 1)
        error_handler();
     if (fscanf(fp, "%14s\n", flights[n_flights].departDay) != 1)
        error_handler();
     ++n_flights;
}
...

附录: 根据 Chux 的建议,我修改了代码以减轻潜在的缓冲区溢出,方法是将 scanf 最大字符串长度设置为 29(比 char[30] 缓冲区大小小 1)。

这里有更详细的解释:

SonarSource: "scanf()" and "fscanf()" format strings should specify a field width for the "%s" string placeholder

关于c - 在 C 中,如何将文本文件的不同行保存到不同的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53402869/

相关文章:

c - Wireshark - 以编程方式修改 pcap 文件中的数据包

c++ - FindFirstFile() 显示地址

c - fread 在不是 eof 时返回零

C - 如何计算字符串中的确切单词数? (不包括该单词位于另一个单词内部的时间)

java - 如何使 XML 文档无需中间文件存储即可下载?

java - 打开并写入文件 Java

javascript - 将文本文件解析为数组?

java - 异常说明 "Resetting to invalid mark "在标记 inputStream 并重置它时出现,对于大文件。?

.net - Windows服务无法复制到文件共享

c - Linux 设备驱动程序,是否可以使用文件描述符获取次要编号?