0% found this document useful (0 votes)
2 views

lab11

This C program converts the contents of an input file to uppercase and writes it to an output file. It requires exactly two arguments: the input file path and the output file path. The program handles file opening, reading, writing, and error reporting, while tracking the total number of bytes written to the output file.

Uploaded by

Lfy Dun
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

lab11

This C program converts the contents of an input file to uppercase and writes it to an output file. It requires exactly two arguments: the input file path and the output file path. The program handles file opening, reading, writing, and error reporting, while tracking the total number of bytes written to the output file.

Uploaded by

Lfy Dun
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <sys/types.

h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

#define BUFFER_SIZE 512

char to_upper(char c) {
if (c >= 'a' && c <= 'z') {
return c -= 32;
} else {
return c;
}
}

int main(int argc, char *argv[]) {


if (argc != 3) {
printf("ERROR: 3 arguments expected, but %i was given.\n", argc);
return 1;
}

int in_fd = open(argv[1], O_RDONLY);


if (in_fd < 0) {
printf("OPEN FOR READ ERROR: %s\n", strerror(errno));
return 1;
}

int out_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0666);


if (out_fd < 0) {
printf("OPEN FOR WRITE ERROR: %s\n", strerror(errno));
close(in_fd);
return 1;
}

long long bytes_written = 0;

char buffer[BUFFER_SIZE];

while (1) {
ssize_t bytes_read = read(in_fd, buffer, BUFFER_SIZE);
if (bytes_read == 0) {

break;
} else if (bytes_read < 0) {
printf("READ ERROR: %s\n", strerror(errno));
break;
}

for (int i = 0; i < bytes_read; i++) {


buffer[i] = to_upper(buffer[i]);
}

ssize_t bytes_written_out = write(out_fd, buffer, bytes_read);


if (bytes_written_out < 0) {
printf("WRITE ERROR: %s\n", strerror(errno));
break;
}

bytes_written += bytes_written_out;
}

close(in_fd);
close(out_fd);

printf("Total bytes written: %lld\n", bytes_written);

return 0;
}

You might also like