Вопрос

I am trying to read integers from a txt file and store them in an 1D array.I have tried several ways but doesn't work correctly. My text file is below

1 2
2 1
3 2
2 1
1 2
2 1
3 2
2 1
1 2
2 1
3 2
2 1

Here is my code

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

int main(void) // usually we write void when main doesn't take args
{
    int i;
    int j;

    /*matrix*/

    int *mat = malloc((12* 2* sizeof ( int))); // no casting!


    FILE *file;
    file=fopen("test.dat", "r");   // extension file doesn't matter
    if(!file) {
        printf("File not found! Exiting...\n");
        return -1;
    }

    for(i = 0; i < 12; i++)
    {
        for(j = 0; j < 2; j++)
        {
            if (!fscanf(file, "%d", &mat[i*2 + j])){
                printf("error!\n");
                break;
            }

            //fscanf(file, "%d", &mat[i*2 + j]);
            printf("ok!\n");

            printf("%d \t",mat[i*2 + j]); // mat[i][j] is more clean
        }
        printf("\n");

    }

    free(mat);
    fclose(file);

    return 0;
}

Thank you for helping! ******UPDATE**** I figure out the first problem is that I couldn't read the file but then I found that I could only print one value which is 1 instead of 24 values there

./print_mat 
ok!
1   error!

error!

error!

error!

error!

error!

error!

error!

error!

error!

error!

error!
Это было полезно?

Решение

The code is fine. The reason for a possible segmentation fault, is that the file could not be open (maybe file could not be found).

A problem may occur if the file doesn't contain as much data as you expect.

You could check that like this:

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

int main(void) // usually we write void when main doesn't take args
{
    int i;
    int j;

    /*matrix*/

    int *mat = malloc((12* 2* sizeof ( int))); // no casting!


    FILE *file;
    file=fopen("test.txt", "r");   // extension file doesn't matter
    if(!file) {
        printf("File not found! Exiting...\n");
        return -1;
    }

    for(i = 0; i < 12; i++)
    {
        for(j = 0; j < 2; j++)
        {
            if (!fscanf(file, "%d", &mat[i*2 + j]))
                break;
            printf("ok!\n");

            printf("%d\n",mat[i*2 + j]); // mat[i][j] is more clean
        }

    }

    free(mat);
    fclose(file);

    return 0;
}

Why not to cast what malloc returns.

[EDIT]

A better error output could be done like this:

if(!file) { // equivalent to file == NULL
    perror("File not found! Exiting...\n");
    return -1;
}

Now, when the file could not be opened, you would get the output I have inside perror and a message for the error.

I tried to open a file that it didn't exist and got

File not found! Exiting...
: No such file or directory

Probably you do not have the file in the same directory as your main file.

Credits to Olaf Dietsche and pmg for their comments.

As another answer states, you can always use a debugger to find where is the problem. Many people use valgrind.

As OP found out, scanf() will fail to parse the file when the values are separated by comma and not by space.

Другие советы

I've tested your program and on my configuration it worked without throwing errors.

What is the configuration of your machine? Compiler etc.?

Maybe you should check out the tool valgrind to find memory leaks during execution, see: http://www.cprogramming.com/debugging/valgrind.html It helped me to trace some seg faults.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top