使用系统调用和打印行读取文件

时间:2015-10-21 14:48:27

标签: c printf output system-calls

该程序读取文本文件" hello.txt"并查找其中出现的字符串w并打印行号和整行。它还会打印文件中字符串w的次数。程序编译没有错误,这里是代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>

int main() {

    int fd;
    char c;
    char str[152];
    int i = 0, j = 0;
    int bytesread;
    int flag = 1;
    int found = 0;
    int line = 1;
    int foundflag = 1;

    char w[] = {'h', 'e', 'l', 'l', 'o'};
    int len = strlen(w);

    if ((fd = open("hello.txt", O_RDONLY, 0)) != -1) { //if 1

        bytesread = read(fd, &c, 1);
        str[j] = c;
        j++;

        if (bytesread != -1) { //if 2

            while (bytesread != 0) { //while

                if (c == '\n')
                    line++;

                if (c == w[i]) { //if 3
                    i++;
                    flag = 0;
                } else if (flag == 0 || i == len) //end of f3
                { // else 3
                    i = 0;
                    flag = 1;
                }// end of else 3
                else if (flag == 1) {
                    while (read(fd, &c, 1)) {
                        str[j] = c;
                        j++;
                        if (c == ' ')
                            break;
                        if (c == '\n') {
                            line++;
                            break;
                        }
                    }
                }

                bytesread = read(fd, &c, 1);
                str[j] = c;
                j++;

                if ((c == ' ' || c == '\n') && flag == 0 && i == len) {
                    found++;
                    foundflag = 0;
                    printf("w was found in line %d.\n", line);
                }

                if ((c == '\n')&&(foundflag == 0)) {

                    for (j = 0; str[j] != '\n'; j += 5) {
                        printf("%c", str[j]);

                        if (str[j + 1] != '\n')
                            printf("%c", str[j + 1]);
                        else {
                            j++;
                            break;
                        }

                        if (str[j + 2] != '\n')
                            printf("%c", str[j + 2]);
                        else {
                            j += 2;
                            break;
                        }

                        if (str[j + 3] != '\n')
                            printf("%c", str[j + 3]);
                        else {
                            j += 3;
                            break;
                        }

                        if (str[j + 4] != '\n')
                            printf("%c", str[j + 4]);
                        else {
                            j += 4;
                            break;
                        }
                    }

                    for (; str[j] != '\n'; j++)
                        printf("%c", str[j]);

                    printf("\n");
                    j = 0;

                } else if (c == '\n')
                    foundflag = 1;

            } //end of while
            printf("w has occured %d times.\n", found);

        } else //end of if 2
            printf("couldn't read file.\n");

    } else //end of if 1
        printf("Couldn't open file for read.\n");

    close(fd);
} //end of main

这是终端的输出:

w was found in line 1.
hello
w was found in line 2.
w was found in line 6.
hello world
hellooooo
w has occured 3 times.

以下是&#34; hello.txt&#34;的内容:

hello
hello world
hallo
I'm here
we're here
hello
hellooooo

输出中打印的行数为1,2&amp; 6,但这是输出应该是什么样的:

w was found in line 1.
hello
w was found in line 2.
hello world
w was found in line 6.
hello
w has occured 3 times.

1 个答案:

答案 0 :(得分:4)

  1. 我建议你阅读一些C材料。您的代码表明您对语言知之甚少。
  2. 我不会改变你的代码,因为那很难。
  3. 我会发布我的代码的相关部分并解释这些内容。
  4. 所以,代码位:

    const char fname[] = "hello.txt";
    const char w[] = "hello";
    
    (...)    
    
    while (read(fd, &buffer[i], 1) == 1) {
        /* end of line */
        if (buffer[i] == '\n' || buffer[i] == 0x0) {
            buffer[i] = 0;
            if (!strncmp(buffer, w, strlen(w))) {
                printf("w was found in line %d\n", line);
                puts(buffer);
                n++;
            }
            line++;
            i = 0;
            continue;
        }
        i++;
    }
    

    说明

    1. <强> while (read(fd, &buffer[i], 1) == 1) : 这将读取fd中的一个字符(由之前的open调用返回)并将其存储在缓冲区[i]中。这里要注意的相关事项是,在此之前,您应该声明int i = 0并确保buffer是已定义的数组或malloc内存区域。这个while将一直持续到读取的字节数不同于1(这就是我们要求的)。

    2. if (buffer[i] == '\n' || buffer[i] == 0x0) :此if检测到行尾。非常直截了当。

    3. buffer[i] = 0; if (!strncmp(buffer, w, strlen(w))) buffer[i] = 0会将当前缓冲区的最后一个字符设置为零。这样做是为了摆脱我们读过的最后一个\n,所以我们可以用puts很好地打印它。我在评论中建议的位是使用strncmp。此函数与strcmp类似,但它只会比较最多定义的字节数。因此,使用此函数,您可以有效地确定字符串是否以您要查找的子字符串开头。如果找到这个字符串,我们打印它所在的行,打印缓冲区本身并递增n,这是我们计算w次的计数器。您应该在代码的开头声明int n = 0; ...

    4. line++; i = 0; continue; :这位于行尾检测if内。所以,这样做是为了增加我们的行计数器,将i设置为零 - 这很重要,因为在新行中我们将读取一个新的缓冲区,并且该缓冲区索引必须从0开始。{ {1}}强制循环重复而不执行其余代码。

    5. 最后,continue范围的其余部分定义为 while 。由于我们的while循环在每个字符处执行,因此在读取每个字符后,缓冲区索引必须递增。

    6. 我测试的文件是您提供的文件。我得到的输出是:

      i++