简体   繁体   English

如何打印当前行?

[英]How do I print the current line?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()

{
    int i, f=0;
    int c;
    char file_name[100];
    char  search[10];

    printf("Enter the file name:");
    scanf("%s", file_name);
    printf("Search word:");
    scanf("%s", search);

    FILE *f = fopen((strcat(file_name, ".txt")), "rb");
    fseek(f, 0, SEEK_END);
    long pos = ftell(f); 
    fseek(f, 0, SEEK_SET);

    char *bytes = malloc(pos);
    fread(bytes, pos, 1, f);
    fclose(f);

/*search*/

    if (strstr(bytes, search) != NULL){
      printf("found\n");
       f = 1;}
      else{
    printf("Not found\n");

    f=0;}

    if (f==1){    /* if found...print the whole line */
     ....}
  free(bytes);

}

Above stated is my program for searching a string from .txt file. 上面说的是我从.txt文件中搜索字符串的程序。 When found, it prints "found", else it prints "Not found". 找到后,将打印“找到”,否则将打印“未找到”。 Now I want to print the complete line of which the string was a part. 现在,我想打印出该字符串是其中一部分的完整行。 I was thinking of using 'f==1' as the condition for 'if found' print the whole line, not really sure what is the best way to proceed. 我当时正在考虑使用“ f == 1”作为“如果找到”的条件来打印整行,而不是真的确定最佳的处理方法。

First you need to fix your read to leave the data you read from the file NUL-terminated: 首先,您需要修正读取操作,以保留从NUL终止文件中读取的数据:

char *bytes = malloc(pos + 1);
fread(bytes, pos, 1, f);
bytes[ pos ] = '\0';

Add some error checking too - Check the return from malloc() and fread() . 也添加一些错误检查-检查malloc()fread() it's a good habit to get into. 这是一个好习惯。

Then, if you find your string, split what you read at that point: 然后,如果找到您的字符串,请拆分当时读取的内容:

char *found = strstr( bytes, search );
if ( found != NULL )
{
    *found = '\0';
    char *lineStart = strrchr( bytes, '\n' );
    char *lineEnd = strchr( found + 1, '\n' );
        .
        .

I'll leave it up to you to figure out what it means if either or both of those are NULL. 我将由您自己决定这两个中的一个或两个均为NULL的含义。

Also, using fseek() to figure out how many bytes are in a file is technically wrong as ftell() doesn't return a byte offset but only a value that can be used by fseek() to return to that same spot in the file. 同样,使用fseek()找出文件中有多少字节在技术上是错误的,因为ftell()不会返回字节偏移量,而只会返回fseek()可以使用的值以返回文件中的同一位置。文件。 There are some architectures out there where ftell() returns a meaningless number. 在某些体系结构中,ftell()返回无意义的数字。

If you want to know how big a file is, use stat() - or fstat() on an open file: 如果您想知道文件的大小,请在打开的文件上使用stat()fstat()

struct stat sb;
FILE *f = fopen(...)
fstat( fileno( f ), &sb );
off_t bytesInFile = sb.st_size;

Note also that I didn't use long - I used off_t . 另请注意,我没有使用多long -我使用过off_t Using long to store the number of bytes in a file is a recipe for serious bugs when file sizes get over 2 GB for 32-bit programs. 当32位程序的文件大小超过2 GB时,使用long在文件中存储字节数会导致严重的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM