Home > Software design >  File lines concatenation
File lines concatenation

Time:02-05

i have a method that is supposed to print file lines concatenated with other file lines, basically what i wanted to is is that if we have a file1 with this data

111100000
111001000
111000100

and file2 with this data

0

it supposed to returns 1 file1_lines file2_lines so for this one it should returns

11111000000
11110010000
11110001000

Here is what I tried to do so far:

#include <stdio.h>
#include <stdlib.h>
#define TAILLE_MAX 10000


void assemblage_fichier(const char *file1, const char *file2){
    FILE *fichier1, *fichier2;
    fichier1 = fopen(file1, "r");
    fichier2 = fopen(file2, "r");
    char c[TAILLE_MAX], c2[TAILLE_MAX];
    
    if(!fichier1 || !fichier2){
        printf("cannot open file \n");
        exit(0);
    }
    
    while (fgets(c, sizeof(c), fichier1) && fgets(c2, sizeof(c2), fichier2))
    {
        printf("1%s%s\n", c, c2);
    }
    
    fclose(fichier1);
    fclose(fichier2);
}


int main(int argc, char const *argv[])
{
    assemblage_fichier(argv[1], argv[2]);
    return 0;
}

by the way my code returns:

11111000000

so it does the job for only one line.

CodePudding user response:

fgets(c, sizeof(c), fichier1) && fgets(c2, sizeof(c2), fichier2) will only evaluate to true if and only if both fgets(c, sizeof(c), fichier1) and fgets(c2, sizeof(c2), fichier2) are successful. However, since fichier2 only has 1 line, fgets(c2, sizeof(c2), fichier2) returns NULL after the first iteration (since it reaches the end of the file). From the fgets() man page:

fgets() returns s on success, and NULL on error or when end of file occurs while no characters have been read.

That is why you see only one line being printed.

basically in python double for loops in two files lines reads first file line then all of the second file lines then moves to file1 second lines and does the same job, i dont know how t do that in c

Well, nested loops exist in C as well. Try changing this section of your code:

while (fgets(c, sizeof(c), fichier1) && fgets(c2, sizeof(c2), fichier2))
    {
        printf("1%s%s\n", c, c2);
    }

to something like this (the comments in the code point out the changes I've made):

while (fgets(c, sizeof(c), fichier1)){ //read one line from fichier1 at a time
    c[strcspn(c, "\n")] = 0; //for removing the newline as suggested by pmg
    while (fgets(c2, sizeof(c2), fichier2)){ //this loop reads from fichier2 until it reaches the end of the file
        printf("1%s%s\n", c, c2);
    }
    rewind(fichier2); //for changing the file position indicator for fichier2 to the beginning of the file since the file position indicator is at the end of fichier2 when the loop ends
 }
  •  Tags:  
  • Related