Something wrong with the output!

I want to edit the text file so it has more space between successive lines, but there are some weird characters also added at the beginning of the file, which i dont know why.

Help me correct my code, thank very much :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>
#include <string.h>

int main()
{
  FILE* fFile;
  char str[50], editedContent[500];

  if ((fFile = fopen("lab2.txt", "r+")) == NULL)
    {
      printf("Can not open file for reading.\n");
      return 1;
    }
  while (fgets(str, 50, fFile) != NULL)
    {
      strcat(editedContent, str);
      strcat(editedContent, "\n");
    }

  //reset position to the beginning of the file and write new content
  rewind(fFile);
  fputs(editedContent, fFile);

  fclose(fFile);
  return 0;
}


This is the content of lab2.txt before and after editing:
1
2
3
4
5
1
2
3
4
5


1
2
3
4
5
6
7
8
9
4³p·1

2

3

4

5
Try initializing editedContent with empty string.
1
2
char s[]="";
strcpy ( editedContent, s );
It worked, thank :)
But I still dunno why is that, this example I read below still work without initializing string

http://www.cplusplus.com/reference/cstring/strcat/
Last edited on
abhishekm71 wrote:
Try initializing editedContent with empty string.

1
2
char s[]="";
strcpy ( editedContent, s );

Better would be to use actual initialization:
char str[50]={}, editedContent[500]={};


kradragon94 wrote:
But I still dunno why is that, this example I read below still work without initialize the string
strcpy does not rely on the contents of the destination string.

ok.. thanx cire, for pointing out the simpler option.
Didn't know that even char arrays could be initialized in such a manner.
Topic archived. No new replies allowed.