How to split a text file using tab space in c?

后端 未结 3 839
情书的邮戳
情书的邮戳 2021-01-26 10:44

I am doing a socket programming for that I having the following details in the text file. I want to split that text file using tab space and I need to assign them to the variabl

3条回答
  •  被撕碎了的回忆
    2021-01-26 11:01

    Here is a sample code to read line-by-line from file and split strings at tab character.

    strtok modifies the source string passed and it uses static buffer while parsing, so it's not thread safe. If no delimiter is present in the line then the first call to strtok returns the whole string. You need to handle this case.

    void split_string(char *line) {
        const char delimiter[] = "\t";
        char *tmp;
    
        tmp = strtok(line, delimiter);
        if (tmp == NULL)
        return;
    
        printf("%s\n", tmp);
    
        for (;;) {
            tmp = strtok(NULL, delimiter);
            if (tmp == NULL)
                break;
            printf("%s\n", tmp);
        }
    }
    
    int main(void)
    {
        char *line = NULL;
        size_t size;
        FILE *fp = fopen("split_text.txt", "r");
        if (fp == NULL) {
            return -1;
        }
        while (getline(&line, &size, fp) != -1) {
            split_string(line);
        }
    
        free(line);
        return 0;
    }
    

提交回复
热议问题