[Courses] [C] Lesson 13: exc1 answer, problem on exc2
Morgon Kanter
admin at surgo.net
Thu Dec 5 18:58:08 EST 2002
I'll start with my exercise 1 answer first. Unlike exc2, it uses file
descriptors unneedingly.
/********* BEGIN EXC 1 **********/
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
int main(int argc, char *argv[]) {
unsigned int number_of_lines = 0;
int fd;
FILE *file;
int input;
if(argc != 2) {
fputs("Error: inproper number of arguments.\n", stderr);
fputs("Usage: ./lines filename\n", stderr);
return -1;
}
fd = open(argv[1], O_RDONLY);
if(errno == ENOENT) {
fputs("Error: No such file by that name.\n", stderr);
return -1;
}
file = fdopen(fd, "r");
while(input != EOF) {
input = getc(file);
if(input == 10) number_of_lines++;
}
printf("There were %i lines in %s\n", number_of_lines, argv[1]);
return 0;
}
/********** END **********/
Output for this:
./exc1 blah
There were 4 lines in blah (note: this is correct)
./exc1 yo
Error: No such file by that name
-----------------
Okay, here is exercise 2. I'm having a bit of trouble in this one because in
the output file, it copies correctly but it adds the character "y" with a
sideways-colon over top of it on a newline. Any ideas why?
/************** BEGIN EXERCISE 2 ***************/
/* All tabs will be expanded to FOUR spaces. Insane
* people who keep pushing for 8 space tabs!
*/
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[]) {
FILE *file_read;
FILE *file_write;
int current_char;
if(argc != 3) {
fprintf(stderr, "Error: Improper use of arguments.\n");
fprintf(stderr, "Usage: exc2 copyfile createdfile\n");
return -1;
}
file_read = fopen(argv[1], "r");
if(errno == ENOENT) {
fprintf(stderr, "Error: No such file.\n");
return -1;
} else if(file_read == NULL) {
fprintf(stderr, "Error: Wrong permissions on file-to-copy.\n");
return -1;
}
file_write = fopen(argv[2], "w");
if(file_write == NULL) {
fprintf(stderr, "Error: No write permissions.\n");
return -1;
}
while(current_char != EOF) {
current_char = fgetc(file_read);
if(current_char == 9) {
fputs(" ", file_write);
} else {
fputc(current_char, file_write);
}
}
fclose(file_read);
file_read = NULL;
fclose(file_write);
file_write = NULL;
printf("Copied %s to %s with expanded tabs.\n", argv[1], argv[2]);
return 0;
}
/************ END **************/
Morgon
--
grab my updated (11/25/02) public key from http://www.surgo.net/pubkey.asc
More information about the Courses
mailing list