[英]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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.