0

I'm trying to read a txt file containing a "picture" (a matrix of chars) and ftell and fseek seem to be working in a different way than what i was taught in class and on the web.

Here is the code:

fp = fopen(filename, "r");
checkFopen(fp);

findRowsAndCols(fp, &rows, &cols);

for (i = 0; i < cols; i++)
    {
        fseek(fp, i, SEEK_SET);
        for (j = 0; j < rows; j++)
        {
            ch = fgetc(fp);
            if (ch != ' ')
            {
                //doing something with ch..
            }

            test1 = fseek(fp, (cols-1), SEEK_CUR);
            test2 = ftell(fp);
        }
    }
//cols = 9 (int)

Instead of jumping 8 characters in the file the cursor is moved only by 3 test1 is always 0 while test2 is increased twice by 4 than by 5 and by 6..

This is a very weird behavior for a program in my opinion. What am I doing wrong?

Edit:

the text file:

12345678\n

9!@#____\n

________\n

________\n

________\n

I'm trying to read the file char by char going through each column from top to bottom.

The first char I get is '1' then '5' and then '\n'

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    `fseek(fp, i, SEEK_SET);` will seek to absolute byte offset `0` in the first loop iteration, offset `1` in the second, `2` in the third, etc. – Andrew Henle May 30 '17 at 11:58
  • 2
    I'm not sure _exactly_ what you're doing wrong, but using `fseek` and `ftell` on a text file is almost never the right approach. It would help if you could show us an example of the file format you're trying to read, and it would also help if you explained which operation you thought would "jump 8 characters in the file" and why. – zwol May 30 '17 at 11:59
  • 1
    You are seeking `cols-1` characters from the current position. What do you think where your position would be? – Holger May 30 '17 at 12:01

0 Answers0