0
  • 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; 
}
RandomMath
  • 675
  • 15
  • 33
  • can you specify the format of the file that you would like to read in? What are columns separated with? – gen Feb 11 '16 at 19:59
  • They are exactly the way the matrix is shown above. --> I will attach a file – RandomMath Feb 11 '16 at 20:00
  • Please read some books (see http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). I think, answering this question is no good. –  Feb 11 '16 at 20:00
  • 2
    You don't set columns back to 0 when you start reading a new line. – Barmar Feb 11 '16 at 20:04
  • So the number of columns is just the number of #s in the first row? – gen Feb 11 '16 at 20:07
  • @gen - yes the number of # in a row – RandomMath Feb 11 '16 at 20:09
  • 1
    I recommend you read some existing [examples on stack overflow](https://www.google.com/search?q=stackoverflow+c%2B%2B+read+file+matrix&ie=utf-8&oe=utf-8). The results were found by searching the internet for "stackoverflow c++ read file matrix". – Thomas Matthews Feb 11 '16 at 20:18

1 Answers1

0

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);
sameera sy
  • 1,708
  • 13
  • 19