0

The objective of my program that I need to write is that it will read in a line from a file ONLY ONCE (meaning when you read it once you should not go back to the file and read it again), and it should store that line in an array of chars. The size of the array must be just big enough to hold the line of text in. Also, it is recommended to not use getchar, and instead use fgets.

user2969777
  • 665
  • 1
  • 5
  • 4

3 Answers3

0

Worst case, there is only one line of text in the file, so you would need to get the file size and allocate that much memory for the buffer.

#include <io.h>
#include <stdlib.h>

long buffLen = _filelength(...);
// check bufLen for errors

char* buffer = (char*)malloc((size_t)buffLen);
// check for allocation failures (it could be an 8 gigabyte file)

If your CRT doesn't support the _filelength posix function, look through this thread, and also keep in mind that a long isn't 64-bits on all platforms, so using a method that returns a 64-bit value is best.

Community
  • 1
  • 1
josh poley
  • 7,236
  • 1
  • 25
  • 25
  • Why is this "worst case"? It's the most convenient case. I wonder what you do in other cases. – jogojapan Nov 29 '13 at 04:47
  • @jogojapan - Worst case for a memory consumption/stability perspective. If you have a 1TB file, you are likely going to have issues; or if each line is only one character long, then you've wasted a bunch of memory. But yes, it is definitely the most convenient case. – josh poley Dec 01 '13 at 04:09
0
  ssize_t getline(char **lineptr, size_t *n, FILE *stream);
  ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
  //this two function will help you,you can man them on linux
sundq
  • 735
  • 2
  • 9
  • 28
0

Loop around fget() until NULL is returned and feof() is true or the data read ends with a \n. For each iteration read in the data into a temporary buffer and append it to a final buffer, which is increased in size accordingly.

alk
  • 69,737
  • 10
  • 105
  • 255