简体   繁体   中英

Reading a file line by line and splitting the string into tokens in c

I am reading a file line by line and splitting the string into tokens.

int main()
{
    FILE* fp;
    char  line[255];

    fp = fopen("file.txt" , "r");
    while (fgets(line, sizeof(line), fp) != NULL)
    {   
        char val1[16];
        char val2[9];

        strcpy(val1, strtok(line, ","));
        strcpy(val2, strtok(NULL, ","));

        printf("%s|%s\n", val1, val2);          
    }
}

My input file content (file.txt)

182930101222, KLA1512
182930101223, KLA1513
182930101224, KLA1514
182930101225, KLA1515

When I print get

 | KLA1512

Instead of

182930101222| KLA1512

What is the issue ?

Your problem (again) is that you're not allocating enough space for an array, and overwriting the end of it. The irony is that in this case, you don't even need to allocate any (additional) arrays. strtok() is tokenizing the line[] array, overwriting the delimiters with '\\0' chars, and those are sufficient for your needs.

int main()
{
    FILE* fp;
    char  line[255];

    fp = fopen("file.txt" , "r");
    while (fgets(line, sizeof(line), fp) != NULL)
    {
        const char* val1 = strtok(line, ",");
        const char* val2 = strtok(NULL, ",");

        printf("%s|%s\n", val1, val2);
    }
}

fgets inserts a newline

simply increase val2 size by 1 ie val2[10]

or remove trailing '\\n'

while( fgets(line, sizeof(line), fp) != NULL ){ 
        char val1[16] ,val2[9];
        char *pos;
        if ((pos=strchr(line, '\n')) != NULL)
            *pos = '\0';
        strcpy(val1 , strtok(line,","));
        strcpy(val2 , strtok(NULL,","));
        printf("%s|%s\n",val1, val2);           
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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