-4

I Couldn't understand this code i've left comment line about strcopy. Can you explain it to me? Thanks already. I'm new at c and trying to improve myself. Sometimes i stuck at somewhere and in this situation i couldn't find any solution.

#include <stdio.h>
#include <string.h>
#define SIZE 1000

int main(){
int lwd,cnt;
char read1[SIZE];
char true;

FILE *r = fopen("test.txt","r");
if(r==NULL){
    printf("Er.");
}
FILE *cpy =fopen("temp","w");
if(cpy==NULL){
    printf("Er.");
    fclose(r);
}
printf("Please enter whic line you wanna remove:");
scanf("%d",&lwd);

while(!feof(r)){
    strcpy(read1,"\0"); // what does it mean?
    fgets(read1,SIZE,r);
    if(!feof(r)){
        cnt++;
        if(cnt != lwd){
            fprintf(cpy,"%s",read1);
        }
    }
}
fclose(r);
fclose(cpy);
remove("test.txt");
rename("temp","test.txt");

FILE *read;
read = fopen("test.txt","r");
if(read == NULL){
    printf("Error.");
    fclose(read);
}
true=fgetc(read);

while(true != EOF){
    printf("%c",true);
    true=fgetc(read);
}
getch();
return 0;

}

Kaan Deniz
  • 23
  • 1
  • 5

2 Answers2

1

The statement

strcpy(read1,"\0");

is just copying an empty string to initialize read1.

It's a silly way to do it; read1[0] = 0; is just as good, but as @chux points out in the comments, initializing read1 isn't necessary, and there are other things wrong with the code (e.g., checking result of fgets).

Doug Currie
  • 40,708
  • 1
  • 95
  • 119
1

You can see the documentation for the strcpy below.
https://i.stack.imgur.com/AN38r.png

You can see the strcpy copies the second string argument in the first string argument. The first argument is the destination where the string is copied. The second argument is the source from which the complete string is copied.

Therefore we can say that the strcpy line is just to ensure that read1 is always empty before the reading the next line.

If we skip this line then a case where the length of the previously read line is more than the current line can give errors. It is almost a redundant step here as fgets replaces the '\n' with '\0'. Thus, characters after that do not matter.