How to allocate memory for a String Dynamically?

前端 未结 4 1232
梦谈多话
梦谈多话 2021-01-26 15:30

I am trying to read Data from a Text file & storing it inside a structure having one char pointer & an int variable. During fetching data from file I know that there wil

相关标签:
4条回答
  • 2021-01-26 15:56

    i assume you open the file in binary mode since you use fseek.

    you could read from the file using fgetc() since you don't know the size just allocate a buffer with some initial size like 100, then read char by char placing them into the buffer. monitor if the buffer is large enough to hold the characters and if not realloc() the buffer to a larger size.

    0 讨论(0)
  • 2021-01-26 16:09

    If you know the position of the first structure, and the position of the second structure, you also know the total length of the first structure (position of second - position of first). You also know the size of the integer part of the structure, and therefore you can easily calculate the length of the string.

    off_t pos1;  /* Position of first structure */
    off_t pos2;  /* Position of second structure */
    
    size_t struct_len = pos2 - pos1;
    size_t string_len = struct_len - sizeof(int);
    
    0 讨论(0)
  • 2021-01-26 16:11

    Either

    1. malloc the maximum possible length
    2. read that much into the malloc'd block
    3. figure out where the real end of the string is
    4. write a \0 into your malloc'd block there so it behaves correctly as a nul-terminated string (and/or save the length too in case you need it)
    5. optionally realloc your block to the correct size

    Or

    1. malloc a reasonable guesstimate N for the length
    2. read that much
    3. if you can't find the end of the string in that buffer:
      1. grow the buffer with realloc to 2N (for example) and read the next N bytes into the end
      2. goto 3
    4. write a \0 etc. as above

    You said in a comment that the max. string length is bounded, so the first approach is probably fine. You haven't said how you figure out where the string ends, but I'm assuming there is some delimiter, or it's right-filled with spaces, or something.

    0 讨论(0)
  • 2021-01-26 16:11

    Did you mean to SEEK_CUR in your second fseek()? if so, then you know the length of the string. Used a fixed sized buffer.

    0 讨论(0)
提交回复
热议问题