簡體   English   中英

如何從C中的文本文件讀取參數

[英]How to read parameters from text file in C

我承擔了從文本文件中讀取參數並根據該參數創建矩陣的任務。 在閱讀數字的那一刻,我已經呆了幾個小時。 它們在測試文件中的組織順序是:

數字 數字 數字 A字母(L或S)

然后還有另一行具有相同的結構。

到目前為止,我的代碼是這樣的:

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

typedef struct matrix {//create a struct of matrix
    int** mat;//the name
    int rows, cols, start;//How many rows and cols + starting number
    char shape;// The shape of the matrix
}matrix;


int** createMat(int r, int c);//Signature of a function #1
int strToInt(char* str);//Signature of a function #2
int CheckName(char A[], char B[]);//Signature of a function #3


int main(int argc, char** argv)//start of the program
{
    matrix mat;//create a matrix
    int lines = 0;//get the number of lines
    FILE* input;//Create a pointer
    char temp[5];//Create a temporary array
    if (argc > 3 || argc < 2)//Check if the number of the parameters is     correct
    {
        printf("There's a wrong number of arguments. Please try again.");
    }
    else
    {
        if (CheckName(argv[1], "input.txt") == 0)//check if the parameter is input.txt
        {
            if (argc == 3)//Check if the third parameter is given.
            {
                lines = strToInt(argv[2]);//fill the number of lines with the number of the lines
            }
            input = fopen(argv[1], "R");//open and read the input file
        }
    }
    return 0;
}

int** createMat(int r, int c)//creat a matrix function
{
    int *arr = (int *)malloc(r * c * sizeof(int));
    return arr;
}

int strToInt(char* str)//insted of atoi function
{
    return atoi(str);
}

int GetNumber(FILE* file)//Get the number function
{
    char ch;//Create a temporary file
    int len;//Create a temporary file
    char temp[5];//Create a temporary array
    while ((ch = fgetc(file)) != ' ')
    {
        len = strlen(temp);
        temp[len] = ch;
        temp[len + 1] = 0;
    }


int CheckName(char A[], char B[])
{
    int result = 1;
    for (int i = 0; A[i] || B[i]; i++)
    {
        if (A[i] != B[i])
        result = 0;
    }
    return result;
}

好像您知道每一行都有那些用空格分隔的項目。

然后,您可以將每一行拆分為令牌。 看看這個問題的答案:

在C中的每個空白處分割字符串

暫無
暫無

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

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