C string is read from the file and display

There is a method feof (fp) that can determine if it is the last end, marked the end of EOF is -1, you can write

	char str[50];
    char *p = str;
    //读文件的一般套路句式
 	if((file = fopen("B.txt","r")) == NULL)
    {
        printf("不能打开文件");
        exit(0);
    }
    //开始循环文件指针
    while (!feof(file))
    {
    	//将获取的文件指针赋值给字符串str
    	//还有一点注意是fgetc(fp)这句话读取一个字节后,光标位置后移一个字节。
    	//那么就不可避免地将-1赋给了*p,也就是str
        *p++ = fgetc(file);
    }
    //str现在结尾是-1,以及后面一堆没有赋值的乱字符,字符串结尾认'\0',
    //需要往前移一位并补上'\0'
    *--p = '\0';
    fclose(file);
    //这样的输出就对了。
    printf("%s\n",str);
Published 163 original articles · won praise 117 · views 210 000 +

Guess you like

Origin blog.csdn.net/u010095372/article/details/88657841