0

I am working in C and have a text file that is 617kb that I am trying to read with fgetc. For some reason fgetc is starting randomly within the file. I have tried moving the file pointer to get beginning with fseek with no success. I can get fgetc work to fine with smaller files. Any help is appreciated.

Sample input is 25,000 lines of data similar to:

Product
23 660
2366 3
237 09
2 3730
23734
23 773
241 46

Source:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void print(FILE *category){

    int ch = 'a';

    while ((ch = fgetc(category)) != EOF){

        printf("%c", ch);
    }

    getchar();
}

int main(void){

    FILE *category = fopen("myFile", "r");

    if (category == NULL){
        puts("category file not found");
    }
    else{

        print(category);    
        fclose(category);

        return 0;
    }

}
Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
TinMan
  • 99
  • 2
  • 13
  • 2
    What tells you that you start reading from the middle of the file? Does you output window truncate? I would modify code to stop writing after 100 characters or so, just to see if the current output scrolled off the screen. – KeithSmith Dec 03 '13 at 01:25
  • … or better, write output to another file instead of the screen. This can be done without modifying the program at all. – Potatoswatter Dec 03 '13 at 01:27
  • @Prashant Your edit took away information. Although your edit nicely formatted the post, OP's “Product\n 23 660\n 2366 3\n 237 09\n 2 3730\n 23734\n 23 773\n 241 46\n” is explicit showing the line-endings incorporated. This is unlike your edit. – chux - Reinstate Monica Dec 03 '13 at 01:28
  • Yes, I removed the `\n`s. In my defense, I copied the sample file (after stripping the `\n`s) and source on my computer and ran it. Unfortunately, I was not able to reproduce the error in the question, as it correctly printed out the entire file, starting from the top. Just tried it again with the `\n`s, same (correct) behavior for me. – Prashant Kumar Dec 03 '13 at 01:29
  • @user3023963 Are there explicit `\n`s in your file? Or were you simply indicating a new line? Perhaps I was too bold in assuming you only meant a new line. – Prashant Kumar Dec 03 '13 at 01:34
  • Only put \n to show new line, It looked confusing in the editor because it all was on one line. – TinMan Dec 03 '13 at 15:43

1 Answers1

0

I suspect the problem lies elsewhere.

Where is the output from this program going? If you're sending it to the console, its scrollback buffer won't be large enough to contain the whole file. Maybe it just looks like fgetc() is starting in an odd place.

Try diverting the output from this program to a new text file and compare the size of this file with the size of the input file, e.g.:

./category_print >output.txt
r3mainer
  • 23,981
  • 3
  • 51
  • 88