0

I would like to read a file to a string.

I have the following code which can be compiled but cannot be run.

My idea is to use a while loop to append every character in the file to the end of the string until EOF.

char string[50000];    

FILE *file;
file = fopen("filename.txt", "r");

char buffer;


while((buffer=fgetc(file)) != EOF)
{
    strcat(string, buffer);
}
Johnson
  • 31
  • 5
  • @SharonJDDorot I would like to change the first line and rewrite it into the file. – Johnson Dec 01 '13 at 16:09
  • So instead open the file as a+ or r+ (one of them returns a pointer to the beginning of the file and allows overwriting the text, not sure which), read the first line to a char array, return the pointer to the start of the file and simply overwrite the existing text. Much easier and more efficient. – Sharon Dorot Dec 03 '13 at 13:05

3 Answers3

1

Try setting string[0] to \0 first. Also buffer should be char * and null-terminated as well.

From the man page:

 NAME
 strcat, strncat -- concatenate strings

 LIBRARY
 Standard C Library (libc, -lc)

 SYNOPSIS
 #include <string.h>

 char *
 strcat(char *restrict s1, const char *restrict s2);

 char *
 strncat(char *restrict s1, const char *restrict s2, size_t n);

 DESCRIPTION
 The strcat() and strncat() functions append a copy of the null-terminated
 string s2 to the end of the null-terminated string s1, then add a termi-
 nating `\0'.  The string s1 must have sufficient space to hold the
 result.
ask
  • 2,160
  • 7
  • 31
  • 42
0

The buffer you are reading into has to be an array.

char buffer[50000];
Zero Fiber
  • 4,417
  • 2
  • 23
  • 34
0
  int buffer, i;
  char string[50000];

  FILE *file;
  file = fopen("file.txt", "r");

  i = 0;

  while ( ( buffer = fgetc( file ) ) != EOF ) {
    string[i++] = buffer;
  }

  printf("%s\n", string );
szpal
  • 647
  • 9
  • 27
  • @Johnson: In C, a string is an array of char values terminated by a special null character value '\0'. So, if you mean a string, that it never be 1 character length, but minimum 2 or more. – szpal Dec 02 '13 at 12:32