c-通过从文件中读取,将数字提取到字符串数组中



我有一个跟踪文件,其中有n行,每行的读/写顺序后面跟着一个十六进制32位地址。有点像这样:

read  0x20000064
write 0x20000068
read  0x2000006c

我不能为每一行从文件中仅提取32位地址和读/写(例如20000064(。因此,我打算从文件trace中逐行读取,然后将每一行拆分为两个子字符串,并根据子字符串采取一些操作。

// Read the second part of sub-string and store as str1
address = str1 & 0xffff;
// read first part of sub-string and store as str0
if (str0 == read)
read_count++;
else if (str0 == write)
write_count++;

所以,简而言之,我陷入了把绳子一分为二的困境。我尝试了从strtok()fseek()的所有方法,但都不起作用。

我有跟踪文件的内容

读取0x20000064写入0x20000084读取0x20000069写入0x20000070读取0x20000092

和我尝试的代码

#include <stdio.h>
#include <string.h>
int main() {
FILE *fp;
int i = 0, j = 0, k = 0, n;
char *token[30];
char delim[] = " ";
char str[17], str2[17];
char str3[8];
fp = fopen("text", "r");
while(fgets(str, 17, fp) != NULL) {
fseek(fp, 0, SEEK_CUR);
strcpy(str2, str);
i = 9;
n = 8;
while (str[i] !='' && n >= 0) {
str3[j] = str2[i];
i++;
j++;
n--;
}
str3[j] = '';
printf("%sn", str3);
}
fclose(fp);
}

第页。S这段代码有效,但只适用于第一行,之后我会遇到Segmentation错误。

#include <stdio.h>
#include <string.h>
int main() {
FILE *fp;
int i;
char *token[30];
char delim[] = " ";
char str[17], str2[100][17];
char str3[17];
int n = 9, pos = 0;
fp = fopen("text", "r");
while (fgets(str, 17, fp) != NULL) {
fseek(fp, 0, SEEK_CUR);
strcpy(str2[i], str);
if ((n + pos - 1) <= strlen(str2[i])) {
strcpy(&str2[i][pos - 1], &str2[i][n + pos - 1]);
printf("%sn", str2[i]);
}
i++;
}
fclose(fp);
}

我得到的输出:

20000064
Segmentation fault

我期望的输出:

20000064
20000084
20000069
20000070
20000092

您应该使用sscanf():解析行

#include <stdio.h>
int main() {
char line[80];
char command[20];
unsigned long address;
FILE *fp;
if ((fp = fopen("text", "r")) == NULL) 
printf("cannot open text filen");
return 1;
}
while (fgets(line, sizeof line, fp) != NULL) {
if (sscanf(line, "%19s%x", command, &address) == 2) {
printf("command=%s, address=%xn", command, address);
}
}
fclose(fp);
return 0;
}

最新更新