簡體   English   中英

如果文件與字符串參數部分匹配,如何從文件中返回特定行? [C]

[英]How do I return a specific line from a file if it partially matches a string parameter? [C]

我是C的新手,但我正在嘗試編寫一個函數,該函數根據所使用的參數從文件中返回一行。 它將返回包含該參數的最后一行。 我認為使用一個例子可以更好地解釋:

這是文件的內容:

1 one onehello
2 two twohello
3 one threehello

所以,如果我這樣調用函數:

lineContaining("one")

它應該歸還“一個三個”

這是我到目前為止,它還包括一個測試功能的主函數:

char *readStringedCommand(char *str1)
{
    int size = 1024;
    char *buffer = malloc(size);
    char *result = malloc(size);
    FILE *fp;
    fp = fopen("test.txt", "r");
    while(fgets(buffer, 1024, fp)) //get a line from a file
    {
            printf("while1 entered: %s", buffer);
            int i = 0;
            int j = 0;
            int k = 0;
            while(buffer[i] != '\n') //read all the way to the end of a line
            {
                    printf("while2 entered: %s", buffer+i);
                    k = i;
                    while(buffer[k]==str1[j]) //while two characters match
                    {
                            printf("while3 entered");
                            k++;
                            j++;
                            strcat(result, buffer+k); //append the character to the result

                            if(str1[j] = '\0') //if the next character of str1 is the last one
                            {
                                    strncat(result, buffer+k, 20); //append the rest of buffer to the result
                                    return result;
                                    printf("result = %s", result);
                            }
                    }

                    result[0] = '\0'; //clear result for the next line
                    j = 0; //set str1's position to 0
                    k = 0;
                    i++;
            }

    }
    return "errorrrrrr";
}

int main(int argc, const char* argv[])
{
    int num1 = 1;
    char str1[] = "one onehello";
    int num2 = 2;
    char str2[] = "two twohello";
    int num3 = 3;
    char str3[] = "one threehello";
    hwrite(num1, str1); //a function I made that writes a line to a file
    hwrite(num2, str2);
    hwrite(num3, str3);
    printf("%s", readStringedCommand("one"));
    return 0;
}

好的,這個函數給了我一個錯誤:

while1 entered: 1 one onehello
while2 entered: 1 one onehello
while2 entered:  one onehello
while2 entered: one onehello
Segmentation fault (core dumped)

考慮到它在第三個while循環中給出了錯誤,我認為存在問題。 遺憾的是我不知道這里有什么問題。 我確信在那之后會有更多錯誤,但這個讓我感到困惑。

我的問題:

  1. 如何修復此分段錯誤?
  2. 代碼顯然非常難看,但我很沮喪。有沒有更好的方法來解決這個問題?

感謝閱讀所有這些,我將不勝感激。 =(

編輯:修復你們提出的一些錯誤后,我不再得到分段錯誤。 該函數返回“onehello”,這是錯誤的。 它應該返回“一個三個”。 但我正在取得進步,為此我感激不盡。

if(str1[j] = '\0')

應該

 if(str1[j] == '\0')

你可能想要比較值

如果你的文件缺少換行符,那么循環while(buffer[i] != '\\n')可能不會退出,在.txt文件的最后一行可能會發生什么。

因此,如果我正確理解您的問題,您的目標可以通過更簡單的方式實現:

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

char *readStringedCommand(char *str1)
{
    int size = 1024;
    char *buffer = malloc(size);
    char *result = malloc(size);
    /* Check allocations */
    if (!buffer || !result) {
        fprintf(stderr, "Allocation failure, exiting.\n");
        exit(EXIT_FAILURE);
    }
    result[0] = 0; // 0-terminate result

    FILE *fp;
    fp = fopen("test.txt", "r");
    /* Check whether file was opened successfully */
    if (!fp) {
        fprintf(stderr, "Couldn't open file.\n");
        exit(EXIT_FAILURE);
    }
    while(fgets(buffer, size, fp)) //get a line from a file
    {
        if (strstr(buffer, str1)) { // Check whether the line contains the needle
            strcpy(result, buffer); // Copy the line if it does
        }
    }

    // close file
    fclose(fp);

    // Free memory we don't need anymore
    free(buffer);

    // Now, what if no line contained the needle?
    if (result[0] == 0) {
        // Hmm, maybe
        free(result);
        return NULL; // ?
    } else {
        return result;
    }
}

只需使用標准庫中的strstr來檢查每行中是否包含str1 ,將包含它的每一行復制到result ,忽略其他行。 然后在結尾, result包含包含str1的最后一行 - 如果有的話。

如果您不想要整行,而只需str1第一次出現的str1開始的部分,請捕獲strstr返回的指針,並將其用作strcpy的源:

char *needle;
if ((needle = strstr(buffer, str1))) {
    strcpy(result, needle);
}

暫無
暫無

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

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