我正在从一本书中学习C,以下练习之一是:


  编写一个程序,将文件的每一行的m至n列写入stdout
  让程序从终端窗口接受m和n的值。


经过数小时的尝试,我无法忽略n之后的字符,然后转到下一行并开始搜索列号m。我的代码输出也不正确,并且我已经花了两个多小时不知道有什么问题或如何解决。我的测试文件的内容是:

abcde
fghij
klmno
pqrst
uvwxyz


我得到的输出是

bc


我该怎么办?

我也不太喜欢我实现程序的方式(具有两个测试(c = getc(text)) != EOF的while循环。这一切似乎让我感到费解,但我不知道该如何解决

#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;
}

09-10 04:26
查看更多