2015-04-12 59 views
0
#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); 

} 

以上是我從.txt文件中搜索字符串的程序。找到後,打印「找到」,否則打印「未找到」。現在我想打印字符串是其中一部分的完整行。我正在考慮使用'f == 1'作爲'if if'打印整行的條件,但不確定最佳的處理方式。如何打印當前行?

+0

如果你關心線條,你的代碼應該包括一些提到的線段結尾,非? –

+0

從找到匹配的位置向後搜索,直到找到一行結尾(或文件的開頭)。現在向前搜索,直到下一行結束(或文件末尾)。什麼是你的現行路線。 – tux3

+0

如何向後搜索? – jimo

回答

0

首先,你需要修復你的念想離開你從文件中讀取數據NULL結尾:

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

添加一些錯誤檢查過 - 檢查從malloc()fread()回報。這是一個很好的習慣。

然後,如果你發現你的字符串,分裂您在這一點上讀到的東西:

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

我會讓你來弄清楚這是什麼意思,如果那些一方或雙方爲NULL。如果ftell()不返回字節偏移量,但只返回fseek()可用於返回的值,則使用fseek()來計算文件中有多少字節在技術上是不正確的文件中的相同位置。有一些架構在那裏ftell()返回一個無意義的數字。

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

還請注意,我沒有使用long - 我用off_t:在一個開放的文件或fstat() -

如果你想知道一個文件有多大,使用stat()。使用long來存儲文件中的字節數是32位程序文件大小超過2 GB時出現嚴重錯誤的祕訣。

+0

打印'lineStart'在行首打印字符串,而打印'lineEnd'則跳過當前行的其餘部分並打印所有下一行直到文件結束。爲什麼會這樣? – jimo