简体   繁体   English

从C中的txt文件解析和拆分字符串

[英]Parsing and splitting a string from txt file in C

I'm new into C and I got an assignment to read line by line from .txt file and parse some strings into matrix where first line is first row, second line is second row etc. This is what I have in my text.txt file: 我是C语言的新手,我得到了从.txt文件逐行读取并将其解析为第一行为第一行,第二行为第二行等的矩阵的任务。这就是我在text.txt中拥有的内容文件:

07 45 C4 16 0F 02 19 0I 17 0G 
09 45 C4 15 0E 03 11 0A 12 0B 13 0C
13 45 C4 13 0C 03 19 0I 11 0A 17 0G 14 0D 16 0F
05 45 C4 18 0H 01 12 0B

This is what I was able to do so far: 到目前为止,这是我能够做到的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *Read(char filename[]);

void split(char *content);

int main(void){

    char filename[] = "text.txt";
    char *content = Read(filename);
    split(content);
    return 0;
}

char *Read(char filename[]){

    char *buffer;
    long size;

    FILE *log = fopen("text.txt", "r");
    fseek(log, 0, SEEK_END);
    size = ftell(log);
    rewind(log);

    buffer = (char*) malloc(sizeof(char) * size);
    fread(buffer, 1, size, log);
    fclose(log);

    return buffer;
}

void split(char *content){

    char *buffer = strtok(content, " ");
    while(buffer != NULL){
        printf("%s\n", buffer);
        buffer = strtok (NULL, " ");
    }
}

I would really appreciate comments in code because I'm rookie and it would help me to better understand some things. 我真的很感谢代码中的注释,因为我是菜鸟,它将帮助我更好地理解一些东西。

To give you an idea of how it works, I wrote this snippet which manually read the line in that array, supposing that we already know the desired results. 为了让您了解它是如何工作的,我编写了此代码片段,假设我们已经知道所需的结果,可以手动读取该数组中的行。

The following approach cannot be considered the right one. 以下方法不能视为正确的方法。 Ideally you would have a series of rules to split the string, in the following however you have to set the scanf format manually for each line that you want to read. 理想情况下,您将有一系列规则来分割字符串,但是在下面,您必须为要读取的每一行手动设置scanf格式。

Remember to check the return value of scanf, here we should ensure that we have read 7 elements. 记住要检查scanf的返回值,这里我们应该确保已经读取了7个元素。

int main(void) {
    FILE *log;
    char buffer[SIZE];
    char line[SIZE];

    char array[10][10];

    if ((log = fopen("text.txt", "r")) == NULL){
        fprintf(stderr, "Can't open input file!\n");
        return(1);
    }

    while(fgets(buffer, sizeof(buffer), log)){
        int ret = sscanf(buffer, "%2s%2s%2s%4s%2s%4s%4s", array[0], array[1], array[2], array[3], array[4],array[5], array[6]);
        printf("read %d elements\n", ret);
        if (ret != 7) {
           return(1);
        }
        printf("%s", buffer);
    }

    int i;
    for (i=0; i < 6; i++)
        printf("%s\n", array[i]);

    fclose(log);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM