简体   繁体   中英

Read and write a buffer of unsigned char to a file in C?

The following code writes an array of unsigned char (defined as byte ) to a file:

typedef unsigned char byte;
void ToFile(byte *buffer, size_t len)
{
    FILE *f = fopen("out.txt", "w");
    if (f == NULL)
    {
        fprintf(stderr, "Error opening file!\n");
        exit(EXIT_FAILURE);
    }
    for (int i = 0; i < len; i++)
    {
        fprintf(f, "%u", buffer[i]);
    }
    fclose(f);
}

How do I read the file back from out.txt into a buffer of byte ? The goal is to iterate the buffer byte by byte . Thanks.

How do I read the file back from out.txt into a buffer of byte? The goal is to iterate the buffer byte by byte. Thanks.

Something similar to this should work for you. (Not debugged, doing this away from my compiler)

void FromFile(byte *buffer, size_t len)
{

    FILE *fOut = fopen("out.txt", "rb");  
    int cOut;

    int i = 0;
    if (fOut == NULL)
    {
        fprintf(stderr, "Error opening file!\n");
        exit(EXIT_FAILURE);
    }
    cOut = fgetc(fOut);
    while(cOut != EOF)
    {
        buffer[i++] = cOut;  //iterate buffer byte by byte

        cOut = fgetc(fOut);   
    }

    fclose(fOut);
}

If you want to read it back, I wouldn't use %u to write it out. %u is going to be variable width output, so a 1 takes one character, and a 12 takes two, etc. When you read it back and see 112 you don't know if that's three characters (1, 1, 2), or two (11, 2; or 1, 12) or just one (112). If you need an ASCII file, you would use a fixed width output, such as %03u. That way each byte is always 3 characters. Then you could read in a byte at a time with fscanf("%03u", buffer[i]) .

You could (and should) use fread() and fwrite() ( http://www.cplusplus.com/reference/cstdio/fread/ ) for transferring raw memory between FILE s and memory.

To determine the size of the file (to advise fread() how many bytes it should read) use fseek(f, 0, SEEK_END) ( http://www.cplusplus.com/reference/cstdio/fseek/ ) to place the cursor to the end of the file and read its size with ftell(f) ( http://www.cplusplus.com/reference/cstdio/ftell/ ). Don't forget to jump back to the beginning with fseek(f, 0, SEEK_SET) for the actual reading process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM