Home > database >  How to skip further data in file
How to skip further data in file

Time:11-22

I want to read from a (.txt) file's line just 255 bytes (symbols, numbers, whitespaces) and skip the further ones. If there are less than 255 bytes, then read them all, if there are more than 255 bytes, just the first 255 bytes. I am using fgets(string, BUFFER_SIZE (which is 255), myFile). But my file reads all symbols of that line, even if there is more than 255.

My reading loop

    while(fgets(string, BUFFER_SIZE, input))
    {
        fprintf(output, "%s", string);
    }

CodePudding user response:

This might not be the fastest solution, but I found almost all simple file operations in C can be done with simple fgetc/fputc loops. This way, there is no need to worry about buffers... at all.

int n = 0;
int c = fgetc(input);
while (c != EOF) {
   if (c == '\n') {
       n = 0;
   } else if (n >= 255) {
       c = fgetc(input);  // << SNEAKY EDIT
       continue;
   }
   n  = 1;
   putc(c);
   c = fgetc(input);
}

By the way, I just typed this in here, so not tested.

  • Related