簡體   English   中英

在 C 中讀入文本文件,將行分成多個變量

[英]Reading in a text file in C, separate lines into multiple variables

我目前正在開發一個模擬各種 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 變量,然后將后續行讀入數據結構的多個實例(每個進程一個)。

您將需要使用fscanffprintf而不是scanfprintf來執行來自/到文件的 I/O,而不是標准輸入/輸出。

這些被廣泛記錄。 您將使用FILE *變量和fopen & fclose 您甚至可以使用stdinstdoutstderr作為控制台的句柄。

使用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 讀取文件中的行的最佳方法是使用getline()函數。 它比scanf()可靠得多,並且可以自動分配所需的內存。

這是我建議的代碼:

#define _POSIX_C_SOURCE 200809L

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

int main (int argc, char **argv)
{
  FILE *inputfile;

  if (argc < 2)
    {
      fprintf (stderr, "error: missing file name in the arguments\n");
      exit (EXIT_FAILURE);
    }

  inputfile = fopen (argv[1], "r");
  if (!inputfile)
    {
      perror ("myprogram");
      exit (EXIT_FAILURE);
    }

  /* Getting first line */
  char *line = NULL;
  size_t line_size = 0;

  if (!getline(&line, &line_size, inputfile))
    {
      fprintf (stderr, "error: failed to read first line\n");
      exit (EXIT_FAILURE);
    }

  /* Getting the size of the matrix */
  unsigned int size;   /* Size of the matrix */

  if (sscanf (line, "%zd", &size) != 1)
    {
      fprintf (stderr, "error: first line has wrong format\n");
      exit (EXIT_FAILURE);
    }

  /* Getting the content of the matrix */
  int matrix[size][size];

  for (unsigned int i = 0; i < size; i++)
    {
      if (!getline (&line, &line_size, inputfile))
        {
          fprintf (stderr, "error: input file has wrong format\n");
          exit (EXIT_FAILURE);
        }

      /* Copying the items of the line to the matrix */
      char *ptr = line;
      for (unsigned j = 0; j < size; j++)
        {
          matrix[i][j] = atoi(strtok(ptr, " "));
          ptr = NULL;
        }
    }

  free(line);

  return EXIT_SUCCESS;
}

當心,我沒有試過這個代碼...所以,如果有什么地方不能正常工作,我會修復它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM