我是 C 新手,但我正在尝试编写一个函数,该函数根据使用的参数从文件中返回一行。它将返回包含该参数的最后一行。我认为最好用一个例子来解释:
这是文件的内容:
1 one onehello
2 two twohello
3 one threehello
所以,如果我这样调用函数:
lineContaining("one")
它应该返回“one threehello”
这是我到目前为止所拥有的,它还包括一个测试功能的主要功能:
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”。但我正在取得进步,为此我很感激。