Ajouve
Ajouve

Reputation: 10089

Back to the line writing in file C language

I got a new line when I'm writing in a file but I don't understand why:

for(j = 0; j < p_bdClients->tabClient[i].nbComptes; j++){
    fprintf(p_fichier, "%s %f\n",
        p_bdClients->tabClient[i].folios[j].unCompte,
        p_bdClients->tabClient[i].folios[j].solde);
}

I have:

compte1
solde1
compte2
solde2

And I'd like to have:

compte1 solde1
compte2 solde2

I have no newline on p_bdClients->tabClient[i].folios[j].unCompte or p_bdClients->tabClient[i].folios[j].solde.

I tried this:

for(j = 0; j < p_bdClients->tabClient[i].nbComptes; j++){
   printf("%s\n", p_bdClients->tabClient[i].folios[j].unCompte);
}

and I got:

compte1
compte2

But this code:

for(j = 0; j < p_bdClients->tabClient[i].nbComptes; j++){
    printf("|%s| %f\n",
        p_bdClients->tabClient[i].folios[j].unCompte,
        p_bdClients->tabClient[i].folios[j].solde);             
}

gives output as -

| solde1
| solde2

I didn't have the first "|" and p_bdClients->tabClient[i].folios[j].unCompte I don't understand why.

With:

for(j = 0; j < p_bdClients->tabClient[i].nbComptes; j++){
    for(w=0; w<strlen(p_bdClients->tabClient[i].folios[j].unCompte); ++w){
        printf("%02hhx ", p_bdClients->tabClient[i].folios[j].unCompte[w]);
}
}
printf("\n");

I have:

68 79 70 6f 74 68 65 71 75 65 0d 63 68 65 71 75 65 0d 65 70 61 72 67 6e 65 32 0d 
63 68 65 71 75 65 0d 63 61 72 74 65 2d 63 72 65 64 69 74 0d 
68 79 70 6f 74 68 65 71 75 65 0d 63 61 72 74 65 2d 63 72 65 64 69 74 0d 65 70 61 72 67 6e     65 31 0d 63 68 65 71 75 65 0d 65 70 61 72 67 6e 65 32 0d 
63 68 65 71 75 65 0d 63 61 72 74 65 2d 63 72 65 64 69 74 0d 65 70 61 72 67 6e 65 31 0d 
68 79 70 6f 74 68 65 71 75 65 0d 
63 68 65 71 75 65 0d 65 70 61 72 67 6e 65 32 0d 

Thanks for your help

Upvotes: 0

Views: 119

Answers (2)

hyde
hyde

Reputation: 62777

Do you maybe strip newlines (or read data with newlines stripped earlier)? Looks like carriage returns, ASCII 0x0D, visible in hex dump, are not stripped properly. Fix that.

Note that new line in a file may be different combinations of CR (0x0D) and LF (0x0A) ASCII characters, depending on where and how the file was created. LF (Unix) and CR+LF (MS-DOS/Windows) are most common.

In many terminals, printing a CR will move cursor to start of line, and then (without following LF to move to next line) old chars on line will be overwritten, leading to confusing output if this is not intentional.

Upvotes: 1

CAFxX
CAFxX

Reputation: 30291

0x0d at the end of each line (e.g. "68 79 70 6f 74 68 65 71 75 65 0d") is a carriage return. Don't store it in unCompte (or set it to 0x00) and everything will be fine.

Upvotes: 4

Related Questions