How to use the "fread" function in c to read a txt file string and store that string in an array?

Asked

Viewed 3,223 times

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? How vetor is being declared? What is going wrong? Example of the file you want to read? Please provide more details

  • printf is to test if the vector is with the content stored correctly, the contents of the file you are reading

  • What’s going wrong? Example of the file you want to read?

  • Note that you are calling fclose(arquivo_txt) in the event that the fopen(arquivo_txt, "r") failed. This will give you an error. Try to replace the call to fclose() by a return; to prevent the program from going ahead by trying to use the null variable arquivo_txt...

3 answers

1

You are copying 5 bytes of your file to a buffer (vetor) and then calling strlen() in it, which is a function that counts at which position of the vector it receives is the first byte '\0'.

But you didn’t put one '\0' after the end of bytes that you copied, and how the vetor is a local variable, it is allocated to the stack, which does not have its values zeroed.

So unless you guarantee that one of the 5 (why 5?) bytes read is null, you are most likely starting to read the bytes that you carried and going on reading the trash in the rest of the vetor and then going on reading random values on the stack, until it reaches the end of the stack and takes an access violation...

So you have to put after the call to fread() the following line:

vetor[5] = '\0';

Thus the string is delimited and manipulation functions make sense.

-1

this code can help

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

int main()
{
   FILE *fp;
   char c[] = "this is tutorialspoint";
   char buffer[100];

   /* Open file for both reading and writing */
   fp = fopen("file.txt", "w+");

   /* Write data to the file */
   fwrite(c, strlen(c) + 1, 1, fp);

   /* Seek to the beginning of the file */
   fseek(fp, SEEK_SET, 0);

   /* Read and display data */
   fread(buffer, strlen(c)+1, 1, fp);
   printf("%s\n", buffer);
   fclose(fp);

   return(0);
}
  • 2

    I think explaining how to use and then showing the use example is more useful. It also has the fact that you put the fseek in the answer, which is well out of context, and the fwrite, that could be put as an extra in the answer, not in the main scope. Not to mention that it would be a good link of the original content of the tutorialspoint

-1

int c =50; int t=80; c+t=h; printf("%i",h);

  • 3

    Add a brief description explaining why your answer solves the problem.

Browser other questions tagged

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