Home > Mobile >  It takes very long time to read '.txt file' how can i solve this problem? ( C )
It takes very long time to read '.txt file' how can i solve this problem? ( C )

Time:12-09

there is very long "dict.txt" file. the size of this file is about 2400273(calculated by fseek, SEEK_END) this file has lots of char like this 'apple = 사과'(simillar to dictionary)

Main problem is that reading file takes very long time I couldn't find any solution to solve this problem in GOOGLE The reason i guessed is associated with using fgets() but i don't know exactly. please help me

here is my code written by C

#define _CRT_SECURE_NO_WARNINGS

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

int main() {
    int line = 0;
    char txt_str[50];
    FILE* pFile;

    pFile = fopen("dict_test.txt", "r");

    if (pFile == NULL) {
        printf("file doesn't exist or there is problem to open your file\n");
    }
    else {
        
        do{
            fgets(txt_str, 50, pFile);;
            line  ;
        } while (txt_str != EOF);
    }

    printf("%d", line);
    
}

Output

couldn't see result because program was continuosly running

Expected

the number of lines of this txt file

CodePudding user response:

Major

  • OP's code fail to test the return value of fgets(). Code needs to check the return value of fgets() to know when to stop. @A4L
        do{
            fgets(txt_str, 50, pFile);;  // fgets() return value not used.

Other

  • Line count should not get incremented when fgets() returns NULL.

  • Line count should not get incremented when fgets() read a partial line. (I. e.) the line was 50 or longer. Reasonable to use a wider than 50 buffer.

  • Line count may exceed INT_MAX. There is always some upper bound, yet trivial to use a wider type.

  • Good practice to close the stream.

  • Another approach to count lines would use fread() to read chunks of memory and then look for start of lines. (Not shown)

  • Recommend to print a '\n' after the line count.

    int main(void) {
      FILE* pFile = fopen("dict_test.txt", "r");
      if (pFile == NULL) {
        printf("File doesn't exist or there is problem to open your file.\n");
        return EXIT_FAILURE;
      }

      unsigned long long line = 0;
      char txt_str[4096];
   
      while (fgets(txt_str, sizeof txt_str, pFile)) {
        if (strlen(txt_str) == sizeof txt_str - 1) { // Buffer full?
          if (txt_str[sizeof txt_str - 1] != '\n') { // Last not \n?
            continue;
          }
        }
        line  ;
      }

      fclose(pFile);
      printf("%llu\n", line);
    }

CodePudding user response:

fgets returns NULL on EOF.

You are never assigning the result of

fgets(txt_str, 50, pFile);

to txt_str, your program never sees the end of the file and thus enters an endless loop.

try something like this:

char* p_str;

 do{
     p_str = fgets(txt_str, 50, pFile);
     line  ;
 } while (p_str != NULL);
  • Related