Home > Back-end >  What I don't see the content of the file after reading?
What I don't see the content of the file after reading?

Time:12-23

I wrote to file with fwrite and after that, I read the content of file but when I print it into a buffer and print it to stdout by "printf" I see nothing...

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

int main()
{
    uint8_t *my_buffer = malloc(64UL);

    FILE *fp1 = fopen("my_buffer_file", "w");
    fprintf(fp1, "0123456789012345678901234567890123456789012345678901234567890123");
    FILE *my_buffer_fd = fopen("my_buffer_file", "r" );
    int my_new_ret = fread(my_buffer, 1, 64UL, my_buffer_fd);
    int size = my_new_ret;
    printf("my_buffer = |%s|\n", my_buffer);
    printf("size = |%d|\n", size);


    return 0;
}

Someone know why it happens so?

CodePudding user response:

You need to close fp1 before you can read from the same file, like this-

int main()
{
    uint8_t  *my_buffer = malloc(64UL);
    FILE *fp1 = fopen("my_buffer_file", "w");
    fprintf(fp1, "0123456789012345678901234567890123456789012345678901234567890123");

    fclose(fp1);    // New line here

    FILE *my_buffer_fd = fopen("my_buffer_file", "r" );
    int my_new_ret = fread(my_buffer, 1, 64UL ,my_buffer_fd);
    int size = my_new_ret;
    printf("my_buffer = |%s| \n", my_buffer);
    printf("size = |%d|\n", size);
    return 0;
}

Output:

my_buffer = |0123456789012345678901234567890123456789012345678901234567890123| 
size = |64|
  • Related