我正在尝试在 Linux ubuntu 中运行这个 C 编程。我遇到错误分段错误(核心转储)。我正在尝试读取包含以下格式行的文本文件:
key01 value01
key02 value02
key03 value03
这是我的程序。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ARY 50
int main()
{
int i=0;
int numProgs=0;
char* lines[MAX_ARY];
char line[40];
int j;
char search_key[1000];
int position=6, length=5, c = 0;
char str[10];
int ret=0;
char* token;
char* my_key;
FILE *file;
file = fopen("client1.txt", "r");
while(fgets(line, sizeof line, file)!=NULL)
{
//check to be sure reading correctly
//printf("%s", line);
//add each filename into array of programs
lines[i]=malloc(sizeof(line));
strcpy(lines[i],line);
i++;
//count number of programs in file
numProgs++;
}
//check to be sure going into array correctly
for (j=0 ;j<numProgs+1;j++)
{
//printf("%s", lines[j])
;
}
printf("Please enter your search:");
scanf("%s",str);
for(i = 0; i<numProgs; i++)
{
// Gettng the univ names from the list
token = strtok(lines[i]," ");
/* walk through other tokens */
while( token != NULL )
{
ret=strcmp(str, token);
printf("str=%st token=%s ret=%dn", str, token, ret);
token = strtok(NULL," ");
if(ret==0)
{
//now token should be my required token, so break here
break;
}
}
if (ret == 0)
break;
}
printf("Required substring is: %sn", token);
//send(token,to-server1);
fclose(file);
return 0;
}
我无法修复错误。
我刚刚尝试了这个版本的代码(实际上它和你的代码一样,除了两个小的更改)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ARY 50
int main()
{
int i=0;
int numProgs=0;
char* lines[MAX_ARY];
char line[40];
int j;
char search_key[1000];
int position=6, length=5, c = 0;
char str[10];
int ret=0;
char* token;
char* my_key;
FILE *file;
file = fopen("client1.txt", "r");
while(fgets(line, sizeof line, file)!=NULL)
{
//check to be sure reading correctly
//printf("%s", line);
//add each filename into array of programs
lines[i]=malloc(sizeof(line));
strcpy(lines[i],line);
i++;
//count number of programs in file
numProgs++;
}
//check to be sure going into array correctly
for (j=0 ;j<numProgs;j++)
{
printf("%s", lines[j]);
}
printf("Please enter your search:");
scanf("%s",str);
for(i = 0; i<numProgs; i++)
{
// Gettng the univ names from the list
token = strtok(lines[i]," ");
/* walk through other tokens */
while( token != NULL )
{
ret=strcmp(str, token);
printf("str=%st token=%s ret=%dn", str, token, ret);
token = strtok(NULL," ");
if(ret==0)
{
//now token should be my required token, so break here
break;
}
}
if (ret == 0)
break;
}
printf("Required substring is: %sn", str);
//send(token,to-server1);
fclose(file);
return 0;
}
变化 :
1- for (j=0 ;j<numProgs+1;j++)
---> for (j=0 ;j<numProgs;j++)
2-printf("Required substring is: %sn", token);
---> printf("Required substring is: %sn", str);
(如果您尝试打印令牌,它只会打印空)
结论:
您的代码工作正常,请验证文件"client1.txt"是否与您的 .c 文件存在于同一目录中。一般来说,在调用函数后进行测试是一个好习惯,例如(fopen,open,malloc ...等)如果一切顺利