c - 用 C 读取文本文件,将行分成多个变量

标签 c file text input text-files

我目前正在开发一个模拟各种CPU调度方法的程序。目前我的程序要求输入:

printf("Enter type of CPU scheduling algorithm (SJF, RR, PR_noPREMP, PR_withPREMP): ");
scanf("%s", typeOf);

printf("Enter number of processes: ");
scanf("%d", &numPro);

struct processStruct structs[numPro];
int burstTimes[numPro];

for (i = 0; i < numPro; i++) {
    printf("Enter process number: ");
    scanf("%d", &structs[i].pNum);
    printf("Enter arrival time: ");
    scanf("%d", &structs[i].arTime);        
    printf("Enter CPU burst time: ");
    scanf("%d", &structs[i].cpuBur);        
    printf("Enter priority: ");
    scanf("%d", &structs[i].prio);
}

除了两个变量 typeOf(一个 int)和 numPro(一个 char 数组)之外,我还使用了一个数据结构。

这是保存各种参数的数据结构:

struct processStruct {
    int pNum;
    int arTime;
    int cpuBur;
    int prio;
    int waitTim;
};

我想使用与程序输入具有相同信息的文本文件,而不是手动输入。文本文件看起来像这样:

SJF
4
1 0 6 1
2 0 8 1
3 0 7 1
4 0 3 1

第一行是调度算法的名称。 第二行是进程数。 以下几行包含每个进程的信息。因此 1 0 6 1 = 进程 = 1,0 = 到达时间,6 = CPU 突发时间,1 = 优先级

不幸的是,我没有使用 C 语言输入文本文件的经验。有谁知道如何将文本文件中的数据读入变量和数据结构?

谢谢

编辑:我遇到的问题之一是每行的数据不相同。如果只是 4 个数字的行,那就相对容易了。我需要程序将第一行读入 char 数组(字符串),将第二行读入 numPro 变量,然后将后续行读入数据结构的多个实例(每个进程一个)。

最佳答案

使用 fscanf() 可以相当简单地读取该文件,因为除了第一行标识符之外的所有内容都是数字。但您确实需要检查从文件中读取的内容的有效性。我刚刚在错误中使用了 exit(1) 进行说明,它可能比这更复杂(例如错误消息)。

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

#define MAX 100

struct processStruct {
    int pNum;
    int arTime;
    int cpuBur;
    int prio;
    int waitTim;
};

struct processStruct structs[MAX];

int main(int argc, char** args)
{ 
    FILE *fil;
    char typeOf[4];
    int numPro, i;
    if ((fil = fopen("myfile.txt", "rt")) == NULL)
        exit(1);
    if(fscanf(fil, "%4s", typeOf) != 1)
        exit(1);
    if(fscanf(fil, "%d", &numPro) != 1)
        exit(1);
    if(numPro > MAX)
        exit(1);
    for(i=0; i<numPro; i++) {
        if(fscanf(fil, "%d%d%d%d", &structs[i].pNum, &structs[i].arTime,
                                   &structs[i].cpuBur, &structs[i].prio) != 4)
            exit(1);
    }
    fclose(fil);

    // test the result
    printf("Type: %s\n", typeOf);
    printf("Num: %d\n", numPro);
    for(i=0; i<numPro; i++) {
        printf("%d %d %d %d\n", structs[i].pNum, structs[i].arTime,
                                structs[i].cpuBur, structs[i].prio);
    }
    return 0;
}

程序输出:

Type: SJF
Num: 4
1 0 6 1
2 0 8 1
3 0 7 1
4 0 3 1

关于c - 用 C 读取文本文件,将行分成多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36393833/

相关文章:

c - 严格可移植 C 中浮点字节顺序的高效转换

python - 处理对象中的文件

r - 组织子组字符串(文本)

html - 换行时如何使父元素收缩?

c - 高效地重写 for 循环,C

c - C 中结构上的 free() 问题。它不会减少内存使用

c - 指向共享内存中数组的共享指针,指针似乎不共享?

linux - 如何将程序的输出存储到文件中?

javascript - 如何读取非英文字符,如: "Ä,ö" from file in node. js

PHP : Find repeated words with and without space in text