Like unit test C function with FILE * argument

I have a C function uint8_t command_read(const FILE* const in)that is read from in. I would like to write unit test for a function. Is it possible to create FILE*in memory for the test, since I would like to avoid interaction with the file system? If not, what are the alternatives?

+5
source share
1 answer

Is it possible to create a FILE * file in memory for a test?

Of course. To write:

char *buf;
size_t sz;
FILE *f = open_memstream(&buf, &sz);

// do stuff with `f`

fclose(f);
// here you can access the contents of `f` using `buf` and `sz`

free(buf); // when done

This is POSIX. Documents

For reading:

char buf[] = "Hello world! This is not a file, it just pretends to be one.";
FILE *f = fmemopen(buf, sizeof(buf), "r");
// read from `f`, then
fclose(f);

This is also POSIX.

Sidenote:

I would like the test not to interact with the file system.

Why?

+9
source

All Articles