mikael
mikael

Reputation: 41

Copying chars from file into an array

txtfile.txt is a file with 30 lines, each line having 50 characters. I need to copy each character from txtfile into into Carray. How can I do this? I get a segmentation fault when I try.

I have tried the most obvious approach, which is just copying c into the array.

    int cArray[29][49];

    fp = fopen("input_blinker.txt", "r");

    if(fp==NULL){
            perror("Error in opening file");
            return(-1);
    }

    int columnInd = 0;
    int rowInd = 0;

    do {
            c = fgetc(fp);
            if (feof(fp)) {
                    break;
            }
            cArray[rowInd][columnInd] = c;
            columnInd++;

            if (columnInd > 29){
                    rowInd++;
                    columnInd=0;
            }
    } while(1);
    fclose(fp);
    return(0);

I expect the value of c will be copied into the given index of cArray, but I know that isn't correct. Once again, I am getting segmentation fault. Thanks for any help (still learning c)

Upvotes: 0

Views: 48

Answers (1)

dbush
dbush

Reputation: 223872

Your array isn't big enough:

int cArray[29][49];

This creates a 2D array of size 29 x 49. You need an array of 30 x 50:

int cArray[30][50];

Your bounds checks are also incorrect:

        cArray[rowInd][columnInd] = c;
        columnInd++;

        if (columnInd > 29){
                rowInd++;
                columnInd=0;
        }

The size of the second dimension is 49, 50 after fixing it, so you should be checking that value. You should also put in a check to make sure your row index doesn't exceed the bounds of the array.

        if (columnInd >= 50){
                rowInd++;
                columnInd=0;
        }
        if (rowInd >= 30) {
            break;
        }

Upvotes: 3

Related Questions