C - Read file and count rows and columns


  • I am trying to make a function to read a file
  • It should count the rows and columns
  • Set the global variables to be the new rows and columns that were read in

My issue is that I can read the rows, but i can't seem to be able to read the columns right.

File: http://collabedit.com/qjytg

Would anyone be able to help>

matrix: 
#########
#       #
#       #
#       #
#       #
#########


#include <stdio.h>

void read_file(const char *file_name);

size_t rows = 10; 
size_t cols = 20; 

int main(int argc, char *argv[]) {
    //function call

}

void read_file(const char *file_name) {
    FILE *myfile = fopen(file_name, "r");
    int newRows = 0; 
    int newCols = 0; 
    char ch;

    while(!feof(myfile)) {
        ch = fgetc(file);
        if(ch == '\n') {
            newRows++; 
        } else {
            newCols++;
        }
    }
    rows = newRows; 
    cols = newCols; 
}

Answers:


Okay, Here's the small trick or a problem you had to dodge, When you find a new row. You had to make the column count to 0. Which may be you've missed. Replace the if block to the one below and it should work fine

if(ch == '\n') 
{
    newRows++; 
    cols=newCols;
    newCols=0;
}

the fgetc line also has a filename error

ch = fgetc(myfile);