簡體   English   中英

如何多次讀取文件C

[英]How to read file more than once C

我正在嘗試將文件中的單詞列表存儲到char *中 我不假定最大行數或最大字符數。 因此,為了解決這個問題,我決定對.txt文件進行遍歷,以找到行數和最大字符數,以便可以將內存分配給char * list。

但是,當我使用GDB調試程序時,它會跳過文件的第二個運行時間來存儲在單詞中。 為什么要這樣做,我該如何解決? 謝謝!

void readFile(int argc, char** argv)
{
    FILE *myFile;
    char** list;
    char c;
    int wordLine = 0, counter = 0, i;
    int maxNumberOfChars = 0, numberOfLines = 0, numberOfChars = 0;

    myFile = fopen(argv[1], "r");

    if(!myFile)
    {
        printf("No such file or directory\n");
        exit(EXIT_FAILURE);  
    }

    while((c = fgetc(myFile)) !=EOF)
    {
        numberOfChars++;
        if(c == '\n')
        {
            if(maxNumberOfChars < numberOfChars)
                maxNumberOfChars += numberOfChars + 1;

            numberOfLines++;
        }
    }

    fseek(myFile, 0, SEEK_SET);

    list = malloc(sizeof(char*)*numberOfLines);

    for(i = 0; i < wordLine ; i++)
        list[i] = malloc(sizeof(char)*maxNumberOfChars);


    while((c = fgetc(myFile)) != EOF)
    {
        if(c == '\n' && counter > 0)
        {
            list[wordLine][counter] = '\0';
            wordLine++;
            counter = 0;
        }
        else if(c != '\n')
        {
            list[wordLine][counter] = c;
            counter++;
        }
    } 
    fclose(myFile);
}

您需要在第二個循環之前使用fseek重置文件的讀取指針。

添加類似的東西

fseek(myFile, 0, SEEK_SET);

要么

rewind(myFile);

感謝@ ThomasPadron-McCarthy。

首先,您的技術不好,因為它非常慢。 您可以只分配一些內存,然后在需要時使用realloc。

第二:您可以在文件上使用stat()來了解大小。 您將不知道其中的行數,但這可能很有用。

第三:您可以使用fseek()將光標移回文件的開頭,並且通常移至文件內的任何位置。

再次讀取之前,請使用rewind(myFile)。

rewind(myFile)

但是您無需讀取整個文件就可以找出字符數。 您可以使用此結構

struct stat file_stat;
fstat(file_id, &file_stat);
int size_to_read = file_stat.st_size - 1;

您不需要知道行數,因為您可以在行上使用realloc:

list=realloc(list,(sizeof(char*)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM