/* opener.c - Example of how a number of programs (all copies of this one) * can share a file with the first one initializing the content * of the file. * */ #include #include #include #include #include #include #include #include extern int errno; #define LINEMAX 256 int main() { int fd; char line[LINEMAX]; char *datum = "rosanna\n"; char *filename = "moo.foo"; int n; // If file does not exist, create it, // write something to it, and close it. if ((fd = open(filename, O_RDWR | O_CREAT | O_EXCL, S_IRWXU | S_IRWXG | S_IRWXO )) >= 0) { // if it does not exist, create it, write something to it, // and close it. printf("%s already exists\n", filename); write(fd, datum, strlen(datum)); close(fd); } else { if (errno != EEXIST) { perror("Cannot create file"); exit(1); } printf("%s already exists\n", filename); } // Open the file if ((fd = open(filename, O_RDWR)) < 0) { perror("Error opening an existing file"); exit(1); } // Read and print out file's content while ((n = read(fd, line, strlen(datum))) > 0) { line[n-1] = '\0'; printf("line = %s\n", line); } close(fd); return(0); }