Search code examples
carraysfilefgetc

C language, read new line character from external file


Hello guys i have an external file like this :

screenshot

I want to read all character (include space and new line) to my 2-Dimensional(row and column) array, but i failed to do that. Example, in that file at line 10 and column 1 (the bottom left corner) there is a '/' character. I want to put '/' in my array[9][0] (index in array start from 0 not 1), so every character is located in array as same as the file.

Here is my code :

#include <stdio.h>

int main(void) {
/** my index array variable, i for row and j for column */
int i;
int j;

/** varible to read character */
char c;

/** array for the input. The file will not consist more than 17 rows and 2017 columns*/
char input[17][2017];

/** pointer to a file */
FILE *fp;

/** read that file. (my code and that file are located in the same place) */
fp = fopen("bangun.in", "r");

/** start reading the file */
i = 0;
j = 0;
while ( (c = fgetc(fp)) != EOF){
        if (c != 0) {
            input[i][j]=c;
        }
        else if (c == '\n') {
            input[i][j]=c;
            printf("get in");
            i++;
        }
    j++;
}
fclose(fp);
return 0;
}

if my algoritm is worng, could you tell me how to it? my aim is copy all character with the position into my array.


Solution

  • Your if logic is wrong, if c == 0 (else condition) it will never be a new line.