读取.txt文件输入不起作用

时间:2016-09-26 03:29:42

标签: c io

所以我是C的初学者,我试图打开并读取一个文件,将文件的每个元素存储在一个数组中。以下代码似乎应该在实践中起作用,但是当输出给我时

50 2500

无论出于何种原因。如果有人能就我需要解决的问题提供任何帮助,我们将不胜感激

...

3 个答案:

答案 0 :(得分:1)

当你使用fgets()时,你将使用newline char作为分隔符从文件中提取字符串(字符数组)。 fscanf()更适合从文件中提取内容。

程序打印50的原因是因为while循环后magicSquareArray [0]的值是' 2'而不是2,而ascii值是' 2'是50岁。

答案 1 :(得分:0)

像这样的例子

#include <stdio.h>

int main(int argc, char *argv[]){
    char *input = argv[1];//if(argc > 1)
    FILE *inputFile = fopen(input, "r");

    if (inputFile == NULL){
        printf("Cannot open file for reading!\n");
        return -1;
    }

    int n;
    fscanf(inputFile, "%d", &n);//if(1==
    int squareArray[n][n];
    int r, c, v;
    char comma;
    r = c = 0;
    while(2==fscanf(inputFile, "%d%c", &v, &comma)){
        if(comma == ',' || comma == '\n' && c == n-1){//comma == ',' && c < n-1
            squareArray[r][c] = v;
            if(++c == n){
                c = 0;
                ++r;
            }
        } else {
            fprintf(stderr, "input file invalid format\n");
            return -2;
        }
    }
    fclose(inputFile);

    if(r != n || c != 0){
        fprintf(stderr, "It could not be read correctly.\n");
        return -3;
    }

    for(r = 0; r < n; ++r){
        for(c = 0; c < n; ++c){
            printf("%d ", squareArray[r][c]);
        }
        puts("");
    }
    return 0;
}

答案 2 :(得分:0)

您可以使用此功能:

strucT *ReadFromFile (const char *fileName)
{
    printf ("\n***Start function ReadFromFile for file name: %s *** \n" , fileName );   
    strucT *myfilePtr = (strucT*) malloc ( sizeof (strucT) );

    strcpy( myfilePtr->fileName, fileName );    
    myfilePtr->file = fopen ( myfilePtr->fileName , "r");
    int i = 0;

    fscanf( myfilePtr->file , "%d", &myfilePtr->rows);
    printf("rowSize is: %d\n" , myfilePtr->rows);

    fscanf( myfilePtr->file , "%d", &myfilePtr->colus);
    printf("culSize is: %d\n" , myfilePtr->colus);

    myfilePtr->elementNumber = (myfilePtr->rows) * (myfilePtr->colus);
    printf("arraySize is %ld\n", myfilePtr-> elementNumber);

//  myfilePtr->array = (unsigned char*)malloc(sizeof(unsigned char) * (myfilePtr->elementNumber));
    for (i = 0 ; i < myfilePtr->elementNumber; i++)
             {
                fscanf(myfilePtr->file, "%1d", (int*) &myfilePtr->array[i]);    
                //printf("%d" , myfilePtr.array[0]);
            }
// FOR DEBUG    
for (i = 0 ; i < 12 ; i++)
        printf ("%d" , myfilePtr->array[i]);
    printf ("\n");

    fclose(myfilePtr->file);
    printf ("\n***Finish function ReadFromFile for file name: %s *** \n" , fileName );  
    return strucT;
}

此函数读取第一个和第二个int并保存它们。 在此之后,她读取数组值(每个值为1个字符)