简体   繁体   English

C:I / O - 从文件读取整数的最快/最佳方式

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

Trying to work with CI/O currently. 目前正在尝试使用CI / O. I have a file that only holds integers and there is only one per line.. not commas, etc.. what is the best way to read them in: 我有一个只保存整数的文件,每行只有一个..不是逗号等。读取它们的最佳方法是什么:

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

I am creating 2 files which is working fine.. but ultimately, I want to read them both in, join them into one collection, sort them and then print them out to a new file. 我正在创建2个工作正常的文件..但最终,我想要读取它们,将它们连接到一个集合中,对它们进行排序然后将它们打印到新文件中。 There's no need for you to do all that for me, but please help with the above.. here is my effort so far: 你没有必要为我做这一切,但请帮助以上..这是我迄今为止的努力:

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
}

I would suggest you use fgets : 我建议你使用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));

Edit: How to get the number of entries in the file: If you don't keep track of it any other way (like eg having the number of items being the first line), the only solution may be to read the file twice. 编辑:如何获取文件中的条目数:如果您不以任何其他方式跟踪它(例如,将项目数作为第一行),唯一的解决方案可能是两次读取文件。 Once to count the number of lines, and once to read the actual numbers. 一旦计算行数,一次读取实际数字。 Use fseek or rewind after the counting to "rewind" the read pointer to the beginning of the file. 在计数后使用fseekrewind将读指针“倒回”到文件的开头。

I would personally put the counting in a separate function, and also the actual reading. 我个人会把计数放在一个单独的函数中,也是实际的读数。 This way you don't have to duplicate code if you want to read from multiple files. 这样,如果要从多个文件中读取,则不必重复代码。

Your problem can be divided into three different parts: reading in two files, sorting the data, and writing the output into a file. 您的问题可以分为三个不同的部分:读取两个文件,排序数据,以及将输出写入文件。 I am assuming here that the two input files are not already sorted. 我假设这两个输入文件尚未排序。 If they were, the problem would be greatly simplified (google for mergesort if that is the case). 如果是这样的话,那么问题就会大大简化(如果是这样的话,google for mergesort)。

If you want to open a file for reading, you have to use "r" instead of "w" as file open mode flag. 如果要打开文件进行读取,则必须使用"r"而不是"w"作为文件打开模式标志。 In your example code the read/write parts are somehow reversed from what you describe above. 在您的示例代码中,读/写部分以某种方式与您在上面描述的内容相反。 Then you should use fscanf to read formatted input from a FILE*. 然后你应该使用fscanf从FILE *读取格式化的输入。 scanf(...) is just short for fscanf(stdin, ...) . scanf(...)只是fscanf(stdin, ...)缩写。 You can access the files in the following way: 您可以通过以下方式访问这些文件:

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);

Using dynamic memory to store the integers is difficult. 使用动态内存来存储整数很困难。 You need to use realloc to grow a buffer as you write more and more data into it, and finally use qsort to sort the data. 在向其中写入越来越多的数据时,需要使用realloc来增加缓冲区,最后使用qsort对数据进行排序。 Someone else can hopefully give more insight into that if needed. 如果需要,其他人可以希望更深入地了解这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM