I am trying to test fwrite. I am trying to write a usecase in which fwrite fails. Here is waht i tried.
#include <stdio.h>
#include <errno.h>
int main()
{
char arr[6] = "manty";
int ret;
FILE *fp;
printf("Before fwrite - errno - %d\n", errno);
// fp = fopen("fwrite_test.txt", "w+");
ret = fwrite(arr, sizeof(arr) + 2, 1, fp);
printf ("ret - %d errno - %d ferror - %d\n", ret, errno, ferror(fp));
return 0;
}
By wantedly commenting fopen() I thought fwrite will return an error. But it gives a segmentation fault.
How cani test fwrite()?
fwrite(3) may sometimes call the write(2) syscall, but not always, since stdio(3) is buffered (see setvbuf(3) for more). And fwrite
will fail if write
is failing.
You could limit the file size setrlimit(2) with RLIMIT_FSIZE
(and install or ignore a SIGXFSZ
signal(7) handler). In particular by using the ulimit
builtin of bash
shell. Then you could fwrite
a big enough data buffer (larger than the limit). You could also set quotas on a file system (see quotactl(2), quotaon(8) etc...) then write over quota limits. At last, you could write in a small filesystem above its capacities (see Example section of losetup(8) to make a tiny filesystem...). In all these cases write
will fail (so fwrite
too).