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

问题描述 投票:0回答:1

我有一个跟踪文件,其中有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] !='\0' && n >= 0) {
            str3[j] = str2[i];
            i++;
            j++;
            n--;
        }
        str3[j] = '\0';
        printf("%s\n", str3);
    }
    fclose(fp);
}

P.S此代码有效,但仅对于第一行,此后出现分段错误。

#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("%s\n", str2[i]);
        }
        i++;
    }
    fclose(fp);
}

我得到的输出:

20000064
Segmentation fault

我期望的输出:

20000064
20000084
20000069
20000070
20000092
c file-handling c-strings
1个回答
0
投票

您应使用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 file\n");
        return 1;
    }
    while (fgets(line, sizeof line, fp) != NULL) {
        if (sscanf("%19s%x", command, &address) == 2) {
            printf("command=%s, address=%x\n", command, address);
        }
    }
    fclose(fp);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.