简体   繁体   English

在 C 卡住 strcpy

[英]Stucking about strcpy at C

I Couldn't understand this code i've left comment line about strcopy.我无法理解这段代码,我已经留下了关于 strcopy 的评论行。 Can you explain it to me?你能给我解释一下吗? Thanks already.已经谢谢了。 I'm new at c and trying to improve myself.我是 c 的新人,正在努力提高自己。 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;

} }

The statement该声明

strcpy(read1,"\0");

is just copying an empty string to initialize read1 .只是复制一个空字符串来初始化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 (eg, checking result of fgets ).一样好,但正如@chux 在评论中指出的那样,初始化read1不是必需的,并且代码还有其他问题(例如,检查fgets的结果)。

You can see the documentation for the strcpy below.您可以在下面查看 strcpy 的文档。
https://i.stack.imgur.com/AN38r.png https://i.stack.imgur.com/AN38r.png

You can see the strcpy copies the second string argument in the first string argument.您可以看到 strcpy 在第一个字符串参数中复制了第二个字符串参数。 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.因此我们可以说 strcpy 行只是为了确保在读取下一行之前 read1 始终为空。

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'.这几乎是一个多余的步骤,因为 fgets 将“\n”替换为“\0”。 Thus, characters after that do not matter.因此,之后的字符无关紧要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM