1

Possible Duplicate:
How to dynamically allocate memory space for a string and get that string from user?

I have a file. while reading line by line from a file, length of the string is unknown so how to allocate memory for unknown length string in an efficient way.

note:-

each line in a file is seperated by "\n".

programming language - c

Community
  • 1
  • 1
Thangaraj
  • 3,038
  • 7
  • 40
  • 43
  • 3
    http://stackoverflow.com/questions/8164000/how-to-dynamically-allocate-memory-space-for-a-string-and-get-that-string-from-u – Zan Lynx Dec 02 '11 at 17:28
  • See Zan's link. Its always best to look at existing questions before opening a new one. – dbeer Dec 02 '11 at 17:32
  • @dbeer I have searched, I could not find relevant question thats why I have raised it. and the above I did not find as part of this process. any how thanks for the link, but still I am not satisfied with the answer. I am expecting better answer, it would slow down my execution speed. – Thangaraj Dec 02 '11 at 17:36
  • @Thangaraj: It would slow you down? Did you test it? `getc` is actually pretty fast because the underlying `FILE` IO handles IO in large blocks. – Zan Lynx Dec 02 '11 at 17:39
  • @Thangaraj - I fail to see how the link provided doesn't answer your question. – dbeer Dec 02 '11 at 17:55

3 Answers3

6

The general pattern for doing this is

  • Allocate a buffer with malloc of a specified size.
  • Attempt to read into that buffer until you run out of space
  • Use realloc to double the size of the buffer and continue reading
  • Continue with this pattern until the file is completely read
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

One way is to find out the file size via system calls (fstat if I remember correctly). That's not particularly good if the file is very large, as it might potentially not fit in memory.

Another way is to read line by line (or in chunks of n bytes) until you hit the end of file character. See: http://pubs.opengroup.org/onlinepubs/000095399/functions/fread.html

Gigi
  • 28,163
  • 29
  • 106
  • 188
0

You can use malloc, fgets and realloc.

Start with a malloc of fixed size. Perhaps 64 bytes.

Then fgets the size of your string. Check if the end of your string has a \n. If not, realloc the string to double the size. Now fgets some more and repeat until your string ends with a newline or you reach the end of the file.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131