Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如果文件中的特定行与字符串参数部分匹配,如何从中返回该行?[丙]_C_File_Segmentation Fault - Fatal编程技术网

C 如果文件中的特定行与字符串参数部分匹配,如何从中返回该行?[丙]

C 如果文件中的特定行与字符串参数部分匹配,如何从中返回该行?[丙],c,file,segmentation-fault,C,File,Segmentation Fault,我是C新手,但我正在尝试编写一个函数,根据所使用的参数从文件返回一行。它将返回包含该参数的最后一行。我认为最好用一个例子来解释: 以下是该文件的内容: 1 one onehello 2 two twohello 3 one threehello 如果我这样调用函数: lineContaining("one") 它应该返回“一三你好” 到目前为止,我已经完成了以下内容,其中还包括一个测试函数的主函数: char *readStringedCommand(char *str1) { in

我是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循环的错误,我认为问题就在那里。不幸的是,我不知道这里出了什么问题。我确信在那一点之后会有更多的错误,但这一点让我感到困惑

我的问题是:

  • 如何修复此分段错误?
  • 代码显然很难看,但我在C语言方面很差劲。有更好的方法解决这个问题吗?
  • 感谢您阅读所有这些,我将感谢您的帮助=(

    编辑:在修复了你们建议的一些错误后,我不再得到分段错误。函数返回“onehello”,这是错误的。它应该返回“one-threehello”。但我正在取得进展,对此我表示感谢

    if(str1[j] = '\0')
    
    应该是

     if(str1[j] == '\0')
    
    您可能想要比较值


    如果您的文件缺少换行符,则while(buffer[i]!='\n')循环可能不会退出,in.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;
        }
    }
    

    一个问题是
    strcat(result,buffer+k);//将字符追加到结果
    。注释错误,该行将
    buffer
    中的字符串的整个剩余部分从
    buffer[k]
    追加到
    result
    。我认为
    strcat(result,buffer[k])
    可能是正确的方法,但它给了我一个错误:
    传递'strcat'的参数2会使指针从整数变为不带强制转换的整数
    strcat
    不适合这样做。如果要以字符为字符追加字符,请保留一个索引和
    结果[index++]=buffer[k]
    -别忘了在结尾处以0结尾。但这可能仍然不是实现您想要的目标的好方法。不幸的是,您的代码让我感到困惑。我可以为我认为文本要求的内容提供一个简洁的解决方案,但我无法与代码相协调。因此,让我们尝试澄清一下。您想读取一个文件,并在其中找到最后一行t包含一个给定的字符串作为子字符串,是吗?(例如,
    readStringedCommand(“one”)
    不会返回
    “opened”
    ,因为
    “one”
    的字符在该字符串中不连续?@Daniel我想这就是我得到分段错误的地方,我将strcat函数改为
    result[j]=buffer[k] 
    我再也不会收到那个错误了。要回答您的问题,是的,它不会返回“打开”。我将编辑原始帖子,并提供更多关于我所处位置的信息。我完全错过了这一点!!@Shear,但它不会循环到EOF,而while循环只会循环到行的末尾。@LilyBanks是的,你说得对。让我们看看Armin有什么要说的。我也不明白我们怎么能想到第一行没有换行符的另一行。@Shear我几乎100%肯定每行后面都有一个新行字符。@lilybank我也是。毕竟,EOF是在所有行之后出现的。在我跳到上面投票之前,我应该更加小心
    char *needle;
    if ((needle = strstr(buffer, str1))) {
        strcpy(result, needle);
    }