简体   繁体   中英

Splitting string in C by null terminator

I am currently trying to implement a program that intakes a file, reads the file and copies its contents to an array (farray). After this we copy the contents of farray as strings separated by null terminators into a string array called sarray.

For example, say farray contains "ua\\0\\0Z3q\\066\\0", then sarray[0] should contain "ua", sarray[1] should contain "\\0", sarray[2] should contain "Z3q", and finally sarray[3] should contain "66"

However I cannot figure out how to separate the string by the null terminators. I currently can only use the system calls like fread, fopen, fclose, fwrite...etc. Can someone please help me?

src code:

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

int main(int argc, char *argv[]){

    char *farray;
    const char *sarray;
    long length;
    int i;

    //Open the input file
    FILE *input = fopen(argv[1], "rb");
    if(!input){
        perror("INPUT FILE ERROR");
        exit(EXIT_FAILURE);
    }

    //Find the length
    fseek(input, 0, SEEK_END);
    length = ftell(input);
    fseek(input, 0, SEEK_SET);

    //Allocate memory for farray and sarray
    farray = malloc(length + 1);

    //Read the file contents to farray then close the file
    fread(farray, 1, length, input);
    fclose(input);

    //Do string splitting here

    //Free the memory
    free(farray);


    return 0;
}
  1. Keep the number of characters length for further use.

  2. What characters do you want to replace by the null characters? Based on that, walk through farray , replace the appropriate characters by the null character. While doing that, count the number of characters that were replaced by the null characters.

  3. If the number of characters that were replaced by the null character is N, then the array of pointers needs to be of size N+1 .

  4. Allocate memory for the array of pointers.

  5. Walk through farray again and make sure the elements in the array of pointers point to the right location in farray .

Update, in response to OP's comment

In step (2) above, don't replace anything, just compute N.

In step (5), use strdup and assign the returned value to the elements of the array of pointers instead pointing to farray .

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