I am learning C from a book, and one of the exercises is the following:
Write a program that writes columns m through n of each line of a file to
stdout
. Have the program accept the values of m and n from the terminal window.
After hours of trying, I am unable to omit the characters after n
and then go to the next line and start searching for column number m
. My code's output is not right either, and I've been going at this for more than two hours and don't know what is wrong or how to fix it. My test file's content is:
abcde
fghij
klmno
pqrst
uvwxyz
and the output I get is
bc
What do I do?
I also don't really like the way I implemented the program (having two different while loops that test (c = getc(text)) != EOF
. It all seems overly convoluted to me, but I'm unaware as to what I can do to fix it
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
// Ensure correct usage
if (argc != 4)
{
fprintf(stderr, "Usage: ./program <file> <from> <to>\n");
return 1;
}
FILE *text;
int counter = 0, lines = 0, done = 0;
int m = atoi(argv[2]);
int n = atoi(argv[3]);
char c;
// Return if file is NULL
if ((text = fopen(argv[1], "r")) == NULL)
{
fprintf(stderr, "Could not open %s.\n", argv[1]);
return 2;
}
// Write columns m through n of each line
while ((c = getc(text)) != EOF)
{
++counter;
if (c == '\n')
++lines;
if (counter >= m && counter <= n && done == lines)
{
putc(c, stdout);
++counter;
if (counter == n)
{
++done;
while ((c = getc(text)) != EOF)
{
if (c != '\n')
continue;
else
{
counter = 0;
++lines;
putc(c, stdout);
}
}
}
}
}
return 0;
}