#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *input;
char *line;
char *result = NULL;
int length,i;
int buff_size=200;
input = fopen("e:\\kddcup.data_10_percent_corrected","r");
if(input == NULL)
{
printf("\nerror on open e:\\kddcup.data_10_percent_corrected file!");
exit(0);
}
while (fgets( line, buff_size, input ) != NULL) {
result = strtok(line, ","); //read the first attribute
while( result != NULL )
printf( "%s \n", result );
result = strtok(NULL, ","); //continue reading next attribute
} //while end
fclose(input);
}
文件是这样的:
0,tcp,ftp_data,SF,854,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,2,2,0.00,0.00,0.00,0.00,1.00,0.00,0.00,151,119,0.42,0.47,0.41,0.02,0.00,0.00,0.45,0.01,normal.
0,tcp,ftp_data,SF,59,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,12,12,0.00,0.00,0.00,0.00,1.00,0.00,0.00,161,121,0.45,0.44,0.45,0.02,0.00,0.00,0.42,0.01,normal.
0,tcp,ftp_data,SF,854,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,4,4,0.00,0.00,0.00,0.00,1.00,0.00,0.00,171,122,0.49,0.42,0.48,0.02,0.00,0.00,0.40,0.01,normal.
请大家帮忙,谢谢啦
看到了两点:
1)line 未初始化,你下面直接使用了
2)while( result != NULL )
printf( "%s \n", result );
result = strtok(NULL, ","); //continue reading next attribute
这里明显漏了个大括号。
修改如下:
修改的都加了这个//*********************************
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <stdlib.h>
5 int main()
6 {
7 FILE *input;
8 int buff_size=200;
9 char *line = (char*)malloc(buff_size);
10 char *result = NULL;
11 int length,i;
12 input = fopen("e:\\kddcup.data_10_percent_corrected","r");
13
14 if(input == NULL)
15 {
16 printf("\nerror on open e:\\kddcup.data_10_percent_corrected file!");
17 exit(0);
18 }
19 while (fgets( line, buff_size, input ) != NULL)
20 {
21 result = strtok(line, ","); //read the first attribute
22 while( result != NULL )
23 {
24 printf( "%s \n", result );
25 result = strtok(NULL, ","); //continue reading next attribute
26 }
27 } //while end
28 fclose(input);
29
30 }
以上代码可以跑出结果
0
tcp
ftp_data
SF
854
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
2
2
0.00
0.00
0.00
0.00
1.00
0.00
0.00
151
119
0.42
0.47
0.41
0.02
0.00
0.00
0.45
0.01
normal.
0
tcp
ftp_data
SF
59
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
12
12
0.00
0.00
0.00
0.00
1.00
0.00
0.00
161
121
0.45
0.44
0.45
0.02
0.00
0.00
0.42
0.01
normal.
0
tcp
ftp_data
SF
854
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
4
4
0.00
0.00
0.00
0.00
1.00
0.00
0.00
171
122
0.49
0.42
0.48
0.02
0.00
0.00
0.40
0.01
normal.
这个功能直接使用编辑器替换就行,如UltraEdit(正则表达式条件替换更强),除非是必须使用,最好使用工具