I'm putting some very temporary debug prints into various userspace programs to figure out what code runs on an embedded Linux device, and I want these prints to write to a file without leaving it open. To make the debug more portable between the various programs, it would be nice to have a one-liner that can open a file, write to it, and close it without having to define a function/macro elsewhere. I could do something like:
{ FILE *f = fopen("filename", "a"); if (f) { fprintf(f, "DEBUG MSG\n"); fclose(f); } else printf("File open error!\n"); }
which is just removing the whitespace from:
{
FILE *f = fopen("filename", "a");
if (f) {
fprintf(f, "DEBUG MSG\n");
fclose(f);
}
else
printf("File open error!\n");
}
But this feels needlessly complex. Is there some more simplified way of doing this? Again, I'm not talking about making it a function, as I'd like it to be copy/pasted between separate programs without defining a function every time. It's just basically a temporary printk equivalent for userspace.