Jér*_*ôme 2 c parsing filehandle
这是一个经典问题,但我找不到简单的解决方案.
我有一个输入文件,如:
1 3 9 13 23 25 34 36 38 40 52 54 59
2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114
2 4 9 15 23 27 34 36 63 67 76 85 86 90 93 99 108 115
1 25 34 36 38 41 52 54 59 63 67 76 85 86 90 93 98 107 113
2 3 9 16 24 28
2 3 10 14 23 26 34 36 39 41 52 55 59 63 67 76
Run Code Online (Sandbox Code Playgroud)
由空格分隔的不同数量的整数行.
我想用数组解析它们,然后用标记分隔每一行-1
.
困难在于我必须处理整数和换行.
在我的现有代码中,它在scanf循环上循环(因为scanf不能在给定位置开始).
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if (argc != 4) {
fprintf(stderr, "Usage: %s <data file> <nb transactions> <nb items>\n", argv[0]);
return 1;
}
FILE * file;
file = fopen (argv[1],"r");
if (file==NULL) {
fprintf(stderr, "Error: can not open %s\n", argv[1]);
fclose(file);
return 1;
}
int nb_trans = atoi(argv[2]);
int nb_items = atoi(argv[3]);
int *bdd = malloc(sizeof(int) * (nb_trans + nb_items));
char line[1024];
int i = 0;
while ( fgets(line, 1024, file) ) {
int item;
while ( sscanf (line, "%d ", &item )){
printf("%s %d %d\n", line, i, item);
bdd[i++] = item;
}
bdd[i++] = -1;
}
for ( i = 0; i < nb_trans + nb_items; i++ ) {
printf("%d ", bdd[i]);
}
printf("\n");
}
Run Code Online (Sandbox Code Playgroud)
你有很多选择,但一般来说我会如何攻击它:
使用fgets()将输入文件作为文本文件(即一串字符串)读入.这将读取直到线路中断或EOF被击中.使用字符串标记生成器函数扫描每行读取空格并返回空格前的子字符串.您现在有一个整数的字符串表示形式.如果您愿意,可以将其解析为实际的int,或者将子字符串本身存储在数组中.如果你把它切换到int,如果它太大,你需要注意溢出.
归档时间: |
|
查看次数: |
4229 次 |
最近记录: |