简体   繁体   中英

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. 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.

First you need to fix your read to leave the data you read from the file NUL-terminated:

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() . 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.

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. There are some architectures out there where ftell() returns a meaningless number.

If you want to know how big a file is, use stat() - or fstat() on an open file:

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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