简体   繁体   中英

How can I make it so my data doesn't get cut off when reading a file using the read function

main ()
{
    char *temp_list[4096];
    char *list[4096];
    char *token,*token2 = NULL;
    char *ptr;
    int countries;
    ssize_t rd_countries;
    char temp_buf[512];
    char buf[512];
    size_t nbytes;
    char *file_name = "AllCountries.dat";
    int temp = 0;
    int temp2 = 0;
    int i, j = 0;

Here I open the file then later read it.

    countries = open(file_name,O_RDONLY);
    nbytes = sizeof(buf);

I then do a do-while loop to read and tokenize the data by commas but the 512 byte buffer size clips off data and adds more than needed.

    do {
        rd_countries = read(countries, buf, nbytes - 1);
        if (rd_countries>-1) {
            buf[rd_countries] = '\0';
        }

        token = strtok_r(buf, ",", &ptr);
        while (token != NULL) {
            temp_list[i] = strdup(token);
            printf("%s\n  |||||||||||  ", temp_list[i]);
            printf("%s\n", token);
            token = strtok_r(NULL, ",", &ptr);
            i = i + 1;
        }
    printf("-----------");
    } while (rd_countries != 0);

Here's some of the output. As you can see, Eastern Africa turns into Eastern A and frica instead of the correct output because the buffer clips it.

The temp list: IOT
The temp list: British Indian Ocean Territory
The temp list: Africa
The temp list: Eastern A
The temp list: frica
The temp list: 78
The temp list: NULL
The temp list: 0
The temp list: NULL
The temp list: 0
The temp list: British Indian Ocean Territory
The temp list: Dependent Territory of the UK
The temp list: Elisabeth II
The temp list: NULL
The temp list: IO

Read the entire file at once, instead of in 512-byte chunks. You can get the file size with fstat() .

struct stat statbuf;
fstat(countries, &statbuf);
buf = malloc(statbuf.st_size+1);
rd_countries = read(countries, buf, statbuf.st_size);
buf[rd_countries] = '\0';

If you have restriction of 512 bytes then do following.

  • You need to take a variable byte2read inside loop which will see how many bytes are still left in 512 bytes buffer.
  • put a condition check after while loop and see if byte2read > 0.
  • if yes then while reading file again read only 512 - byte2read and pass buf+byte2read as start of your buffer.

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