gpt4 book ai didi

c - 从文件存储中的第一行中的变量中读取 int c

转载 作者:太空宇宙 更新时间:2023-11-04 02:26:50 24 4
gpt4 key购买 nike

我正在尝试从一个 txt 文件中读取整数并将第一行存储到三个变量中,其余的存储到一个数组中。

 while(fgets(lineBuf, sizeof(lineBuf), inputFile) != NULL){

fscanf(inputFile, "%d %d %d", &pages, &frames, &requests);
printf("\n\nin loop to get first line variables:\n Pages: %d\n frames: %d\n requests: %d", pages, frames, requests);
}

输入文件:第一行是前三个数字,之后每一行都是一个数字。

8 12 4 
4
3
4
...

当我运行程序时,它会跳过 12 和 4。

最佳答案

它会跳过,因为您也在使用 fgets 读取文件,所以 fgets 得到第一行,fscanf 第二行,但在输入中保留换行符缓冲区,所以 fgets 将只读取一个空行,等等。混合使用是个坏主意兼具阅读功能。

最好的办法是用 fgets 读取所有行并用sscanf。使用 sscanf 的返回值来确定你有多少整数读。从您的输入来看,一行似乎可以有 1、2 或 3 个整数。所以这会做:

char line[1024];
while(fgets(line, sizeof line, inputFile))
{
int pages, frames, requests, ret;

ret = sscanf(line, "%d %d %d", &pages, &frames, &requests);

if(ret < 1)
{
fprintf(stderr, "Error parsing the line, no numbers\n");
continue;
}

if(ret == 1)
{
// do something with pages
} else if(ret == 2) {
// do something with pages & frames
} else if(ret == 3) {
// do something with pages, frames and requests
}
}

编辑

根据您的评论,只有第一行有 3 个值,其余的每一行都有一个值,那么你可以像这样简化代码:

#include <stdio.h>

int parse_file(const char *fname, int *pages, int *frames, int *request, int *vals, size_t size)
{
size_t idx = 0;

if(fname == NULL || pages == NULL || frames == NULL
|| request == NULL || vals == NULL)
return -1;

FILE *fp = fopen(fname, "r");
if(fp == NULL)
{
fprintf(stderr, "Cannot open %s\n", fname);
return -1;
}

if(fscanf(fp, "%d %d %d", pages, frames, request) != 3)
{
fprintf(stderr, "Wrong format, expecting pages, frames and requests\n");
fclose(fp);
return -1;
}

// reading all other values and storing them in an array
while((idx < size) && (fscanf(fp, "%d", vals + idx) == 1)); // <-- note the semicolon

fclose(fp);
return idx; // returning the number of values of the array
}

int main(void)
{
int pages, frames, request, vals[100];

int num = parse_file("/your/file.txt", &pages, &frames, &request,
vals, sizeof vals / sizeof vals[0]);

if(num == -1)
{
fprintf(stderr, "Cannot parse file\n");
return 1;
}

// your code

return 0;
}

关于c - 从文件存储中的第一行中的变量中读取 int c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49908464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com