我正在从一本书上学习 C,其中一个练习如下:
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.
经过几个小时的尝试,我无法省略 n
之后的字符,然后转到下一行并开始搜索列号 m
。我的代码的输出也不正确,我已经研究了两个多小时,但不知道出了什么问题或如何修复它。我的测试文件的内容是:
abcde
fghij
klmno
pqrst
uvwxyz
我得到的输出是
bc
我该怎么办?
我也不太喜欢我实现该程序的方式(有两个不同的 while 循环来测试 (c = getc(text)) != EOF
。这一切似乎都太过分了让我很困惑,但我不知道我能做些什么来解决它
#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;
}
最佳答案
#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;
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 (counter >= m)
{
putc(c, stdout);
if (counter == n)
{
while ((c = getc(text)) != EOF)
{
if (c == '\n')
{
counter = 0;
putc(c, stdout);
break;
}
++counter;
}
}
}
}
putc('\n', stdout);
return 0;
}
关于c - 打印文件每行的 m 到 n 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49484563/