Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <string.h>
- #include <errno.h>
- #include <unistd.h>
- int main(int argc, char *argv[]) {
- char* source;
- char* destination;
- // take program arguments
- if (argc != 3) {
- printf("Bad call. Syntax: 'filtertouppercase source destination'\n");
- return 1;
- }
- else {
- source = argv[1];
- destination = argv[2];
- }
- // open source
- int source_fd = open(source, O_RDONLY); // source file descriptor
- if (source_fd == -1) {
- printf("Error opening source file. Aborting...\n");
- return 2;
- }
- // check for destination and confirm overwrite
- if (access(destination, R_OK) != -1) {
- printf("The output file already exists. Confirm overwrite? Y/N\n");
- char answer;
- scanf("%c", &answer);
- if (answer != 'Y') {
- printf("Could not write to destination file. Aborting...\n");
- return 4;
- }
- }
- // open destination (create if it doesn't exist, wipe it if it does)
- int destination_fd = open(destination, O_WRONLY | O_CREAT | O_TRUNC);
- if (destination_fd == -1) {
- printf("Error opening destination file. Aborting...\n");
- return 5;
- }
- // read text in 1KB chunks, convert them, and write them
- char chunk[1024];
- // first read
- int chunk_size = read(source_fd, chunk, 1024);
- if (chunk_size == -1) {
- printf("Error reading from source file. Aborting...\n");
- return 3;
- }
- while (chunk_size > 0) {
- // conversion
- for (int i = 0; i < chunk_size; i++) {
- if (chunk[i] >= 'a' && chunk[i] <= 'z') {
- chunk[i] += 'A' - 'a';
- }
- }
- // writing
- write(destination_fd, chunk, chunk_size);
- // reading
- chunk_size = read(source_fd, chunk, 1024);
- }
- // close files
- close(source_fd);
- close(destination_fd);
- printf("Program finished execution succesfully.\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement