简体   繁体   中英

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

Trying to work with CI/O currently. 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. 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 :

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.

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

If you want to open a file for reading, you have to use "r" instead of "w" as file open mode flag. 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*. scanf(...) is just short for 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. Someone else can hopefully give more insight into that if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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