Read a txt file and place each character in a position of an array in C

Asked

Viewed 1,461 times

2

I tried the code below, but it didn’t work

The big problem is fscanf placing each character of the text in an array position

#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{

int a;
char texto[1000];

FILE *file;
file = fopen("texto.txt", "r");

//fscanf(file, " %c", &texto);
fscanf(file, " %c", texto);

if (file == NULL) {
printf("Arquivo nao pode ser aberto\n");
return 0;
}


a=0;
do{
printf("%c", texto[a]);
a++;
} while (a<1000);

}

2 answers

3


#include <stdio.h>
//#include <iostream>

//using namespace std;

int main()
{

    int a;
    char texto[1000];

    FILE *file;
    file = fopen("texto.txt", "r");

    if (file == NULL)
    {
        printf("Arquivo nao pode ser aberto\n");
        return 0;
    }

    a=0;
    char ch;
    while( (ch=fgetc(file))!= EOF ){
        texto[a]=ch; //Aqui cada caractere é colocado no array
        a++;
    }
    texto[a]='\0';

    fclose(file);

    int tamanho = strlen(texto); //Define o tamanho do texto que foi lido
    a=0;
    do{
        printf("%c", texto[a]);
        a++;
    } while (a<tamanho); //Exibe apenas o que foi lido

}
  • 2

    You forgot to put one '\0' after the last character copied from . txt; depending on the values previously in the stack, this can cause the strlen(texto) issues a protection breach (GPF, Segfault, etc.)

  • Thank you, I added in the reply.

  • 1

    Thank you, that’s exactly what I needed.

1

Another variant, taking advantage of the string format of fscanf:

#include <stdio.h>

int main(){
  char texto[1000];
  FILE *file;

  if((file = fopen("texto.txt", "r")) == NULL){
     fprintf(stderr,"Erro na abertura \n");
     return 1;                        // codigo de erro (dif. de 0)
  }
  fscanf(file,"%1000[^\f]",texto);    // ler até formfeed ou fim de ficheiro
  printf("%s",texto);
  return 0;                           // 0 -- sucesso
}
  • %1000[^\f] - read until it is \f or end of file, not exceeding 1000 characters;
  • Normally the value convention to return from main is: ok - 0; error#0
  • 10m indenting code, save 20 on shrink

Browser other questions tagged

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