How to add a string to a C file?

Asked

Viewed 159 times

0

I am having a hard time passing a string to a C file. It turns out that every time I try to write something to be sent to the file, not all the desired information appears.

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

#define N 200
#define O 200

void ler_arquivo(FILE* f, char* vet){

while(fgets(vet, N, f) != NULL){
        printf("%s", vet);
    }
}

int main(){
    setlocale(LC_ALL, "portuguese");
    char cad[N];
    int valor;
    char prod[O];

    printf("-X-X-X-X-X-DADOS DOS PRODUTOS-X-X-X-X-X-:\n ");

    FILE* f1 = fopen("Produtos.txt", "rt");
    if(f1 == NULL){
        printf("Erro de abertura no arquivo");
        exit(1);
    }
    ler_arquivo(f1, cad);
    fclose(f1);

    printf("\nDeseja adicionar algo? SIM = 1 / NÃO = 0: ");
    scanf("%d", &valor);

    /*Até aqui o programa está ok*/

    if(valor == 1){// criei o if para saber se o usuário deseja adicionar
    f1 = fopen("Produtos.txt", "a+");
        if(f1 == NULL){
        printf("Erro de abertura no arquivo");
        exit(1);
        }
    printf("\nDIGITE SEQUENCIALMENTE O NOME DO PRODUTO, QUANTIDADE E PREÇO: ");// para n criar mtas variáveis achei melhor fazer dessa forma a inserção na lista
    scanf("%s", &prod);
    gets(prod);
    fprintf(f1, "\n%s", prod);
    printf("\nCONTEÚDO ADICIONADO NO ARQUIVO!!\n");
    }
    fclose(f1);

return 0;

You could help me solve this problem?

  • What is the reason for using scanf and then gets? just one of them

  • I was testing checking out some online classes and stuff like... Bad even with and without this gets isn’t working.

  • 1

    Not working in which part? What is the error? What information does not appear?

1 answer

0

if(valor == 1){/* criei o if para saber se o usuário deseja adicionar*/
f1 = fopen("Produtos.txt", "a+");
    if(f1 == NULL){
    printf("Erro de abertura no arquivo");
    exit(1);
    }
printf("\nDIGITE SEQUENCIALMENTE O NOME DO PRODUTO, QUANTIDADE E PREÇO: ");/* para n criar mtas variáveis achei melhor fazer dessa forma a inserção na lista*/
scanf("\n%[^\n]s", prod); /*pega toda a string até encontrar o '\n'*/
fprintf(f1, "%s\n", prod);
printf("\nCONTEÚDO ADICIONADO NO ARQUIVO!!\n");
}
fclose(f1);

I just modified the scanf to get the whole string, including the whitespace. I hope I helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.