简体   繁体   中英

Working with two files in C

I am reading a file named "text.txt" that contains a series of numbers with a space in between. I want to write in a new file named "text_nr.txt", all the numbers in "text.txt" but without repetition! My code runs in an infinite loop at the second while loop, but I can't understand why.

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


int main()
{
    int n=0,m=0,nr;

    FILE *fp1;
    FILE *fp2;
    fp1 = fopen("text.txt","r");
    fp2 = fopen("text_nr.txt","a+");

    while(fscanf(fp1,"%d",&n) != EOF){
        nr=0;
        while(fscanf(fp2,"%d",&m) != EOF){
            printf("%d  %d ",m,n);
            if(n != m) continue;
            else{
                nr++;
                break;
            }
        }   
        if(nr == 0){
            fprintf(fp2,"%d ",n);
        }
    }

    fclose(fp1);
    fclose(fp2);

    return 0;      
}

Your inner loop will not reach the end of file since it won't match your search string if the file starts empty.

You could do the fscanf and check if it's 0 (couldn't find anything) or EOF (hit the end).

Functions like fscanf() return various values like EOF (end of file or error ) or the number of specifiers matched, 0 , 1 , ...

Rather than test for one value code needs to stop on, test against all undesired values.

// while(fscanf(fp1,"%d",&n) != EOF){
while(fscanf(fp1,"%d",&n) == 1){
    nr=0;
    // while(fscanf(fp2,"%d",&m) != EOF){
    while(fscanf(fp2,"%d",&m) == 1){

@William Pursell explained it well

At some point in the input, the format to fscanf doesn't match, so fscanf returns 0 but does not advance the file pointer. So it keeps reading from the same spot and returns 0 each time.

Infinite loop.

Try to use fseek function to move stream pointer inside output file.

 while(fscanf(fp1,"%d",&n) != EOF){

    fseek ( fp2, 0 , SEEK_SET );
    bool flag = false;

    while(fscanf_s(fp2,"%d",&m) != EOF){
        printf("%d  %d ",m,n);

        if(n == m) 
        {
            printf("%d = %d ", m, n);
            flag = true;


            break;
        }
    }   
    if(!flag)
    {
        fseek ( fp2, 0 , SEEK_END );
        fprintf(fp2,"%d ",n);
    }
}

EDIT

Another method is to store written values in array. For this you can use vector.

vector<int> vData;

while(fscanf(fp1,"%d",&n) != EOF){


    bool flag = false;

    for(int i = 0; i < vData.size(); i++)
    {
        if(vData[i] == n)
        {
            flag = true;
            break;
        }
    }

    if(!flag)
    {
        vData.push(n);
        fprintf(fp2,"%d ",n);
    }
}

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