6
When inserting in a text file the characters of a string
in C, blank spaces are ignored. How should I make long sentences within a string have separate words?
Follows the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int op = 10, k;
char str[100], c, arquivo[20];
FILE *fluxo;
do{
printf("Digite:\n1- Criar arquivo\n2- Inserir no arquivo\n3- Ler arquivo\n4- Fechar fluxo\n5- Remover arquivo");
scanf("%d",&op);
switch(op){
case 1:
printf("\nDigite o nome do arquivo: \n");
scanf("%s",arquivo);
fluxo = fopen(arquivo,"w");
if(!fluxo)
printf("\n***Erro ao abrir/criar arquivo!***\n");
break;
case 2:
printf("\nDigite o texto a ser gravado:\n");
scanf("%s",str);
for (k=0;str[k];k++){
c = str[k];
putc(c, fluxo);
}
//fprintf(fluxo, "%s",str);
break;
case 3:
fclose(fluxo);
fluxo = fopen(arquivo, "r");
while(!feof(fluxo)){
fscanf(fluxo,"%c", &c);
printf("%c",c);
}
break;
case 4:
fclose(fluxo);
break;
case 5:
remove(arquivo);
break;
}
}while(op!=0);
fclose(fluxo);
}
I think your problem is not time to write the file, but time to read.
scanf
reads astring
up to the first blank.– C. E. Gesser
It is not the scanf, because the file when I open the target file, it is also without spaces, with all words concatenated.
– user5493
Notice that you’re giving
fscanf
in loop. At eachfscanf
you read a string, up to the space, and put it in the file. But the spaces are ignored, this is normal of thescanf
/fscanf
. If your goal is to copy from one file to another, it is best to usefread
andfwrite
.– C. E. Gesser
The @C.E.Gesser is right. It is better to use the
fgets
.– Luiz Vieira