Walter Palma
Walter Palma

Reputation: 27

C programming Im trying to switch content from 2 txt files

I'm trying to switch the content of 2 txt files, they just have lines with characters.

I tried to do this, the program compiles but doesn't modify anything in the text files. Is there another way to do this?

FILE *f, *p;
char linha[TAM], linha2[TAM];

f =fopen("texto.txt", "r");

if(f==NULL)
{
    printf("Erro ao abrir ficheiro");
    fclose(f);
    return;
}

p =fopen("texto2.txt", "r");

if(p==NULL)
{
    printf("Erro ao abrir ficheiro");
    fclose(p);
    return;
}


while( fgets(linha,TAM,f) != NULL || fgets(linha2,TAM,p) != NULL )
{
    if(strcmp(linha, "") != 0)
    {
        fprintf(p, "%s", linha);
    }

    if(strcmp(linha2, "") != 0)
    {
        fprintf(f, "%s", linha2);
    }
}

fclose(f);
fclose(p);


return 0;

}

Upvotes: 0

Views: 145

Answers (1)

cadaniluk
cadaniluk

Reputation: 15229

As hinted by @PaulStelian direct swapping is problematic. Take swapping two variables as an analogy: for it to work, you must store the data of one variable somewhere temporarily. (Or use XOR-swapping, which is sweet, but hacky and works on binary data.)

Your best bet is probably to duplicate one file and then do swapping like

duplicateFile = copy(file1);
file1 = file2;
file2 = duplicateFile;

For fopen, use the r+ option to open a file for both reading and writing. r merely opens it for reading.

From man fopen:

r Open text file for reading. The stream is positioned at the beginning of the file.

r+ Open for reading and writing. The stream is positioned at the beginning of the file.

Upvotes: 1

Related Questions