簡體   English   中英

C:I / O - 從文件讀取整數的最快/最佳方式

[英]C: I/O - Quickest /best way to read ints from file

目前正在嘗試使用CI / O. 我有一個只保存整數的文件,每行只有一個..不是逗號等。讀取它們的最佳方法是什么:

//WHILE NOT EOF
    // Read a number
    // Add to collection

我正在創建2個工作正常的文件..但最終,我想要讀取它們,將它們連接到一個集合中,對它們進行排序然后將它們打印到新文件中。 你沒有必要為我做這一切,但請幫助以上..這是我迄今為止的努力:

void simpleCopyInputToOutput(void);
void getSortSave(void);

int main()
{
    //simpleCopyInputToOutput();
    getSortSave();

    system("PAUSE");
    return 0;
}

void getSortSave(void)
{
    FILE *fp1;
    FILE *fp2;
    FILE *fpMerged;

    printf("Welcome. You need to input 2 sets of numbers.\n");
    printf("Please input the first sequence. Press 0 to stop.\n");

    if ((fp1 = fopen("C:\\seq1.txt", "w")) == NULL)
    {
        printf("Cannot open or create first file!\n");
        exit(1);
    }

    int num;
    int i = 1;
    while (num != 0)
    {
        printf("Please input value # %d\n", i);
        scanf("%d", &num);

        if (num == 0)
        {
            break;
        }

        fprintf(fp1, "%d\n", num);
        i++;
    }

    printf("Please input the second sequence. Press 0 to stop.\n");
    if ((fp2 = fopen("C:\\seq2.txt", "w")) == NULL)
    {
        printf("Cannot open or create second file!\n");
        exit(1);
    }

    num = -1;
    i = 1;
    while (num != 0)
    {
        printf("Please input value # %d\n", i);
        scanf("%d", &num);

        if (num == 0)
        {
            break;
        }

        fprintf(fp2, "%d\n", num);
        i++;
    }

    fclose(fp1);
    fclose(fp2);

    if ((fp1 = fopen("C:\\seq1.txt", "r")) == NULL)
    {
        printf("Cannot open first file!\n");
        exit(1);
    }

    //WHILE NOT EOF
    // Read a number
    // Add to collection

    //TODO: merge ints from both files, sort and output to new file
}

我建議你使用fgets

char buffer[16];
while (fgets(buffer, sizeof(buffer), fp1))
{
    long value = strtol(buffer, NULL, 10);

    /* Use the value... */
}

/* fgets failed ro read, check why */
if (!feof(fp1))
    printf("Error: %s\n", strerror(errno));

編輯:如何獲取文件中的條目數:如果您不以任何其他方式跟蹤它(例如,將項目數作為第一行),唯一的解決方案可能是兩次讀取文件。 一旦計算行數,一次讀取實際數字。 在計數后使用fseekrewind將讀指針“倒回”到文件的開頭。

我個人會把計數放在一個單獨的函數中,也是實際的讀數。 這樣,如果要從多個文件中讀取,則不必重復代碼。

您的問題可以分為三個不同的部分:讀取兩個文件,排序數據,以及將輸出寫入文件。 我假設這兩個輸入文件尚未排序。 如果是這樣的話,那么問題就會大大簡化(如果是這樣的話,google for mergesort)。

如果要打開文件進行讀取,則必須使用"r"而不是"w"作為文件打開模式標志。 在您的示例代碼中,讀/寫部分以某種方式與您在上面描述的內容相反。 然后你應該使用fscanf從FILE *讀取格式化的輸入。 scanf(...)只是fscanf(stdin, ...)縮寫。 您可以通過以下方式訪問這些文件:

FILE *fin1 = fopen("seq1.txt", "r");
FILE *fin2 = fopen("seq2.txt", "r");
FILE *fout = fopen("out.txt", "w");

if (fin1 && fin2 && fout) {
    // Do whatever needs to be done with the files.
}
if (fout)
    fclose(fout);
if (fin2)
    fclose(fin2);
if (fin1)
    fclose(fin1);

使用動態內存來存儲整數很困難。 在向其中寫入越來越多的數據時,需要使用realloc來增加緩沖區,最后使用qsort對數據進行排序。 如果需要,其他人可以希望更深入地了解這一點。

暫無
暫無

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

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