need help writing this program

0 comments

Solve the following problems in C using the relevant POSIX functions demonstrated in class: open, close, read, write, and lseek. Note that there are higher-level C library functions for file operations (ex. fopen, fclose, fscanf, and fprinf) that you are not permitted to use for this assignment.

Both programs must perform appropriate error checking. Refer to the examples given in class.

Problem 1: Double space a text file. This program will read a text file and copy the text into a new text file, double-spacing the text. For example, if the text file contains:

Apples are red, except when they're green.
Sometimes they're yellow. I don't judge.
Apples are weird. Sometimes they're sweet
and sometimes they're bitter. What's that about?

Then the new text file will contain:

Apples are red, except when they're green.

Sometimes they're yellow. I don't judge.

Apples are weird. Sometimes they're sweet

and sometimes they're bitter. What's that about?

The names of the input file and the new file must be given as command-line arguments. Refer to the examples given in class.

Problem 2: Read specified data from a text file. This program will read data from a text file as specified by command-line arguments and print that data on the screen. The command-line arguments specify which file to read, where in the file the data is located (at which byte the data begins), and how much data to read (how many bytes). For example, if the command-line arguments are

data.txt 17 8

then the program will read 8 bytes starting at byte 17 from the beginning of the file “data.txt”. Suppose this file contains the same text as above:

Apples are red, except when they're green.
Sometimes they're yellow. I don't judge.
Apples are weird. Sometimes they're sweet
and sometimes they're bitter. What's that about?

The program will print “xcept wh”.

example

#include <stdio.h>

#include <fcntl.h>

#include <unistd.h>

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

if(argc < 3) {

printf(“Usage: all_caps <source file> <dest file>n”);

return 0;

}

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

if(inputFile<0) {

printf(“Error: file %s not found.n”, argv[1]); return 0;

} int outputFile = open(argv[2], O_WRONLY|O_CREAT, 0644);

if(outputFile<0) {

printf(“Error: cannot create file %sn”, argv[1]); return 0;

}

char buffer; int bytesRead = read(inputFile, &buffer, 1);

while(bytesRead == 1) { if (‘a’ <= buffer && buffer <= ‘z’) {

buffer = ‘A’ + (buffer – ‘a’);

}

write(outputFile, &buffer, 1); bytesRead = read(inputFile, &buffer, 1);

}

close(inputFile);

close(outputFile);

return 0;

}

About the Author

Follow me


{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}