【发布时间】:2018-09-04 04:34:39
【问题描述】:
我正在从一本书中学习 C,其中一个练习如下:
编写一个程序,将文件每一行的 m 到 n 列写入
stdout。 让程序从终端窗口接受 m 和 n 的值。
经过几个小时的尝试,我无法省略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;
}
【问题讨论】:
-
我建议您使用调试器并单步执行程序。当它做出令人惊讶的事情时,请查看所有相关变量。
标签: c string file text printing