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

后端 未结 3 842
情书的邮戳
情书的邮戳 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:15

    You can implement a simplistic parser with sscanf() or strtok() but be aware that neither of these will handle empty fields correctly. scanf's %[^\t] conversion specifier will fail if there are no characters before the next tab, and strtok() will consider any sequence of tabs a single delimiter.

    Here is a solution with an ad hoc utility function that behaves similarly to strtok() but without its shortcomings:

    #include 
    #include 
    
    char *getfield(char **pp, char sep) {
        char *p, *res;
        for (res = p = *pp;; p++) {
            if (*p == sep) {
                *p++ = '\0';
                *pp = p;
                return res;
            }
            if (*p == '\0')
                return NULL;
        }
    }
    
    int main() {
        char line[256];
        char filename[] = "input_file.txt";
        int lineno = 0;
        FILE *fp = fopen(filename, "r");
        if (fp != NULL) {
            while (fgets(line, sizeof line, fp)) {
                char *p = line;
                char *reference = getfield(&p, '\t');
                char *description = getfield(&p, '\t');
                char *quantity = getfield(&p, '\t');
                char *price = strtod(getfield(&p, '\n');
                lineno++;
                if (price != NULL) {
                    /* all fields were parsed correctly */
                    printf("reference: %s\n, reference);
                    printf("description: %s\n, description);
                    printf("quantity: %d\n, atoi(quantity));
                    printf("price: %.2f\n\n, strtod(price, NULL));
                } else {
                    fprintf(stderr, "%s:%d: invalid line\n", filename, lineno);
                }
            }
            fclose(fp);
        }
        return 0;
    }
    

提交回复
热议问题