Error in storing names in.txt file

Asked

Viewed 56 times

0

#include <stdio.h>

//inicio do programa

main()

{ //cria estruturas

typedef struct {

char nome[10];

} movimentacoes;


//cria as variavéis

FILE *arq;

movimentacoes nome;

//recebe o nome da conta

int i;

for(i=0;i<5;i++){

printf("Digite o nome:\n ");

gets(nome.nome);

}

//abre o arquivo para gravação

arq = fopen ("nomes.txt", "a");


//grava os dados no arquivo

fprintf(arq,"%s", nome.nome);


//fecha o arquivo


fclose (arq);



}  

You’re only storing the last name placed (anyone who wants to edit is welcome,)

  • Exactly, you are putting the opening, recording and closing of the file out of the loop and therefore will only do so for the last data read. If you want to record 5 files then put the file handling instructions inside the loop.

  • truth, what a key does not.. kkk

  • I did here, stored all 5, but the last one came first, it’s not necessarily a mistake,

  • Are you sure that the file no longer existed previously created on an execution of the version of the program with error? Note that you are using append.

  • For this case specifically it would be better if you open the file, make a loop reading and writing each name and at the end close the file. You can also open the file with "w" to recreate it every run of the program.

  • I’ll check if it exists,I tried with w but only read the last name

Show 1 more comment

1 answer

2


Usually data structures are declared outside functions.

I noticed some errors in your code:

  • You only declared only one structure instead of an array to receive the names within a loop, in which case each interaction of the loop will overwrite the previous ending with only one name.
  • At the time of writing you write only one name, but if you want to write the 5 names you read, you need to create a loop to iterate over the array and write each name of the array into the file.
#include <stdio.h>

typedef struct {
  char nome[10];
} movimentacoes;

int main() {
  // a - Modo de apender.
  FILE *fp = fopen("nomes.txt", "a");

  // Verifica se houve algum erro ao acessar o arquivo.
  if(fp == NULL){
    printf("O arquivo não existe ou o usuário atual não tem permissão para acessá-lo.");
    return 1;
  }

  // Declara 5 estruturas.
  movimentacoes m[5];

  // Ler 5 nomes.
  for(int i = 0; i < 5; i++) {
    printf("Digite um nome: ");
    scanf("%s", m[i].nome);
  }

  // Escreve os 5 nomes no arquivo.
  for(int i = 0; i < 5; i++) {
    fprintf(fp, "%s\n", m[i].nome);
  }

  // Fecha o arquivo.
  fclose(fp);

  return 0;
}

Browser other questions tagged

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