簡體   English   中英

在C中的文本文件中搜索特定行

[英]Search for a specific line in text file in C

我有一個文本文件,我想從該文本文件中獲取特定行。 文件內容如下所示:

<div class="logo_style">
   <img src="/images/Gnome-Network-Wireless-NoTx-64.png">
   <h2>Fast Actions</h2>
</div>
<div class="container">
   <p><b><font color=green>Action "update_frequency" is sent.</font></b></p>
   <br/><a href="/">[Back To Main Section]</a>
</div>
</body></html>

我只想搜索Action "update_frequency" is sent的行Action "update_frequency" is sent並將其打印到stdout。 我使用了strstr函數,但是當我打印由strstr給定的指針時,它也給出了所有結尾行,它們出現在文本文件中所需的行之后。 所以我試圖將返回的指針存儲在char *str_result 然后我在str_dst復制了str_result的前10個字節,但是我得到的結果是segmentation fault (core dumped) 這是下面的代碼:

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


int main(int argc, char *argv[])
{

    FILE  *file_r;
    char *buffer;
    buffer = malloc (100000);
    char *str_result;
    char str_dst[100];
    file_r= fopen ("file_new.txt", "r");
    fseek (file_r, SEEK_SET, 0);
    while (fgets (buffer, 100000, file_r)!=NULL)
        {
            ;

        }

    str_result = strstr(buffer, "Action");
    memcpy (str_dst, str_result, 10);
    printf("%s\n", str_dst);


    fclose (file_r);
    return 0;
}

有人可以建議我如何只獲得所需的文本行,而不得到strstr所示的其他行嗎?
提前致謝。

memcpy (str_dst, str_result, 10); 不插入/添加NULL終止符。

您必須添加str_dst[10]='\\0'; memcpyprintf之間避免分段錯誤

fgets (buffer, 100000, file_r);
str_result = strstr(buffer, "Action ");//add space
size_t len = strchr(str_result, '<') - str_result;//length upto '<'
memcpy (str_dst, str_result, len);
str_dst[len] = '\0';//null-terminate
printf("%s\n", str_dst);

將文本文件視為充滿字符的數組。 創建幾個整數變量並使它們保持為0。創建一個for循環,如果出現一個特定字母,則使其中一個變量等於找到字符的數組中的位置。 接下來,考慮另一個特定字符,並重復上述相同操作,直到找到它。 讓其中一個變量保存它的位置。 重復此循環,直到為字符串中的所有字符測試了數組。 接下來,創建一系列用於測試整數值的if語句,您可以通過獲取單詞中第二個字母的int位置值,然后從第一個字母的int位置值減去它,然后等於1來做到這一點。該字母2緊接在字母1之后。這似乎令人困惑,這不是一個簡單的解決方法,但我希望這會有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM