2
Hello, I’m trying to read a block of bytes from a file. txt that contains a string for example, I want to store that string in a char array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char nome_arquivo[25];
int i, j;
char vetor[50]; //vetor que receberá a mensagem do arquivo nessa função
//vetor = malloc(50*sizeof(char));
int tamanhovetor;
char cpy[2];
char str[5][9];
printf("Informe o nome do arquivo que deseja abrir:\n");
scanf("%s", nome_arquivo);
arquivo_txt = fopen(nome_arquivo, "r");
if(arquivo_txt == NULL){
fprintf(stderr, "Erro na abertura do arquivo\n");
fclose(arquivo_txt);
}
fread(vetor, sizeof(char), 5, arquivo_txt);
tamanhovetor = strlen(vetor);
printf("%s\n%d", vetor, tamanhovetor);
/*
for(i=0; i<tamanhovetor; i++){
str[i][0]= '\0';
for(j=0; j<9; j++){
sprintf(cpy,"%d", vetor[i]%2);
strcat(str[i], cpy);
vetor[i]/=2;
}
printf("%s ", str[i]);
}*/
}
what the
printf
show? Howvetor
is being declared? What is going wrong? Example of the file you want to read? Please provide more details– mercador
printf is to test if the vector is with the content stored correctly, the contents of the file you are reading
– Italo Zuckerberg
What’s going wrong? Example of the file you want to read?
– mercador
Note that you are calling
fclose(arquivo_txt)
in the event that thefopen(arquivo_txt, "r")
failed. This will give you an error. Try to replace the call tofclose()
by areturn;
to prevent the program from going ahead by trying to use the null variablearquivo_txt
...– Wtrmute