Here is a minimal example that does not do what I expected after the counsel of the user in comments to original question. You can see the issue is not about fflush()
because it is called after the fputs()
:
#include <stdio.h>
int main() {
FILE *test_fileptr;
int errorcode;
errorcode = tmpfile_s(&test_fileptr);
fputs("{}", test_fileptr);
fflush(test_fileptr);
rewind(test_fileptr);
int c;
int read_count = 0;
char buffer[5] = "wxyz";
while(read_count < 4) {
c = fgetc(test_fileptr);
if( feof(test_fileptr) ) {
break;
}
buffer[read_count++] = c;
printf("%c", c);
printf(",%d", c);
}
printf("%s %d", "\ntmpfile return code was", errorcode);
fclose(test_fileptr);
return 0;
}
(The shape of solution attempted here is from the answer at https://stackoverflow.com/a/64550508/1676499 )
I expect the fgetc to find the brace characters, but instead the output is these lines:
,-1 ,-1 ,-1 ,-1
tmpfile return code was 0
As a hint, I am entirely unable to get tmpfile() to return a FILE pointer, yet tmpfile_s() says it succeeds. Why is that?
I can answer my own question now. The problem is permissions. Elevate the process running this code, and the temp file opens. Though, this does not explain why tmpfile_s()
doesn't return an error code:
From https://en.cppreference.com/w/c/io/tmpfile under 'Return Value' :
"Zero if the file was created and open successfully, non-zero if the file was not created or open or if streamptr was a null pointer."
It didn't read from the file, so why did it return 0?