In a C program, i want to read and write to a data file that is set to the owner's exclusive permissions (octal 0600). If the file does not exist, the program creates the empty file with these permissions. My code snippet looks like this:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <time.h>
#include <signal.h>
#include <sys/stat.h>
.
.
.
FILE *fh1;
int fh2;
struct stat st_buf;
int stat_rc;
stat_rc = stat(filename,&st_buf); // check if file exists
if (stat_rc == -1) {
if ((fh2 = open(filename, O_CREAT, 0600)) < 0) { // create empty file w/ 0600 permissions
printf("\n%sCouldn't create '%s'.<br/>",ErrMsg,filename);
return(1);
}
close(fh2); // close newly created file (GENERATES COMPILER WARNING)
}
// normal fopen to add to file, whether empty or existing
if (!(fh1 = fopen(filename,"ab"))) {
.
.
.
This code works fine. It compiles with no errors on my older home (Linux) machine, but on the newer FreeBSD server the compiler generates a warning "implicit declaration of function close(); did you mean pclose()?" I don't honestly know what the diference is between close() and pclose(), nor why the latter would be required for a file opened/created with open().
It is just a compiler warning, and the generated binary executes perfectly. So am currently living with the compiler warning, but it bugs me, and makes me think i'm doing something wrong. It also bugs me not knowing whether the close() is actually closing the file that open() created.
If i knew how to create a file with specific permissions via fopen(), that would serve even better, but i don't know how to do that, nor would i want to employ chmod() or fchmod() when (in most cases) the file already exists, with the correct permissions.