====== Accessing Files ====== ---- ===== Low-level IO with System Calls ===== // gcc -Wall -Werror -Wextra -pedantic -std=c99 write-to-file.c #include #include #include #include #include #include int main(void) { char *pathname = "new.txt"; int flags = O_WRONLY | O_CREAT | O_APPEND; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP; int fd = open(pathname, flags, mode); if(fd == -1) { perror("open() error"); exit(EXIT_FAILURE); } char buf[] = "This is a line.\n"; write(fd, buf, sizeof(buf)); close(fd); return 0; } // gcc -Wall -Werror -Wextra -pedantic -std=c99 copy-file.c #include #include #include #include #include #define BUFSIZE 32768 int main(void) { char buf[BUFSIZE] = {0}; char src_fname[] = "bonding.txt"; char dst_fname[] = "new.txt"; int srcfd = open(src_fname, O_RDONLY); if (srcfd == -1) { perror("Cannot open source file"); exit(EXIT_FAILURE); } int dstfd = open(dst_fname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); if (dstfd == -1) { perror("Cannot open destination file"); exit(EXIT_FAILURE); } int i; ssize_t bytes_read; ssize_t bytes_written; ssize_t total_read = 0; ssize_t total_written = 0; for(i = 0; (bytes_read = read(srcfd, buf, sizeof(buf))) > 0; i++) { bytes_written = write(dstfd, buf, bytes_read); total_read += bytes_read; total_written += bytes_written; printf("[%d] Read %ld bytes from %s and wrote %ld bytes to %s\n", i+1, bytes_read, src_fname, bytes_written, dst_fname); } printf("\nRead %ld total bytes from %s and wrote %ld total bytes to %s " "over %d iterations\n", total_read, src_fname, total_written, dst_fname, i); close(srcfd); close(dstfd); return 0; }