0

Strcat is not working. I am trying to read text from 2 files with a dynamic memory function. I could not understand where is the error.

This is my code:

#include <stdlib.h>
#include <stdio.h>

void fileTest (char* filename, char c[]){

    char* s = (char*) malloc(sizeof(char) * 1000);

    FILE *fp =fopen(filename, "r");
    if (fp == NULL){
        exit(-1);
    }
    while( !feof(fp)){
        fgets(s,100,fp);
        strcat(c,s);
    }

    free(s);
    fclose(fp);


}

int main() {

    char firstS []="";
    char secondS []="";
    fileTest("file.txt", firstS);
    fileTest("file2.txt", secondS);
    printf("Fist file: %s \n", firstS);
    printf("Second file: %s", secondS);

    return 0;
}

In file.txt writes "Hello", in file2.txt writes "World" and I am getting this output : Error Image How can I fix this code?

Ugur A
  • 23
  • 5
  • 1
    Any operation outside of array bounds is Undefined Behavior. So whatever you got as result is ok. You may want to figure out what are sizes of `firstS` and `secondS` (it looks like you think C is some sort of Java/C#/JavaScript in terms of strings... hint - it is not, and there are no strings in C) – Alexei Levenkov Jun 10 '22 at 00:50
  • `char firstS []="";` declares an array of size 1, it can hold only one character, and since you want to use it as a string that's the terminating zero. – Retired Ninja Jun 10 '22 at 01:02
  • [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Retired Ninja Jun 10 '22 at 01:03
  • This is exactly why beginners must study arrays first, then pointers, then strings. C doesn't have a string class and that string class which C doesn't have is not `char`. – Lundin Jun 10 '22 at 09:57
  • I think we desperately need a canonical dupe for "Hi I'm coming from a higher level language and just picked up C and now my string handling program crashes" because questions like this get asked a lot. I wrote a newbie FAQ over at Codidact: [Common string handling pitfalls in C programming](https://software.codidact.com/posts/284849) – Lundin Jun 10 '22 at 10:01

0 Answers0