1

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!
Lbj_x
  • 415
  • 5
  • 15

2 Answers2

3

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.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • Hey it was my typo...thank you for helping now I updated my problem. – Lbj_x May 14 '14 at 09:17
  • @Lbj_x, update your question with the code I provided above, since the code is still the same. – gsamaras May 14 '14 at 09:21
  • Please check my update ... now the problem is that I could only read the first value instead of all my values in the file – Lbj_x May 14 '14 at 09:22
  • I show your update @Lbj_x, but the code you have in the question is still exactly the same as before. I am asking you to update your code too. – gsamaras May 14 '14 at 09:23
  • I updated now, and it returns like the problem shows...I guess its the problem that it didn't skip the space? – Lbj_x May 14 '14 at 09:26
  • Are you sure you are reading the correct file (maybe it is unsaved)? To other users, OP can not chat, since he has small reputation. – gsamaras May 14 '14 at 09:28
  • @G.Samaras I am pretty sure that I read correct file. and then I add another print it shows errors every iteration – Lbj_x May 14 '14 at 09:32
  • I will upvote your question, since you are trying. Maybe we can chat if I do that. Maybe your file contains garbage. I would suggest you to delete the `text.dat`, create another one and copy paste the numbers you have in your question. @Lbj_x I did what I am saying and it works. – gsamaras May 14 '14 at 09:36
  • @G.Samaras I have figure it out, because I use comma instead of space there...my fault – Lbj_x May 14 '14 at 09:36
  • Good that you find it yourself! Bravo! I will update my answer. – gsamaras May 14 '14 at 09:37
  • @G.Samaras Thank you for your kindness, I am really appreciate your help:) – Lbj_x May 14 '14 at 09:40
  • @Lbj_x, you are welcome! But make sure that you learn from this and be more careful next time. A good tip is to think twice before making a comment/edit. :) – gsamaras May 14 '14 at 09:43
0

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.

Peter Ittner
  • 551
  • 2
  • 13