文件读取有问题?
#include<stdio.h>#include<stdlib.h>
int main()
{
int num;
char *c = "abcde",*d;
FILE *fp;
fp = fopen("zuihou.txt","w");
if(fp == NULL)
{
printf("内存分配失败!");
exit(0);
}
fputs(c,fp);
fclose(fp);
fp = fopen("zuihou.txt","r");
fgets(d,6,fp);
fclose(fp);
printf("%s",d);
}
请问一下这段代码为什么会运行出错? 没给读取的字符串分配空间,把char *d 改成char d const char* c = "abcde";
如果你把 "abcde" 视为地址的话,c 必须是个const char* 类型的指针。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num;
const char* c = "abcde";
char* d;
FILE* fp;
fp = fopen("zuihou.txt", "w");
if (fp == NULL)
{
printf("内存分配失败!");
exit(0);
}
fputs(c, fp);
fclose(fp);
fp = fopen("zuihou.txt", "r");
fgets(d, 6, fp);
fclose(fp);
printf("%s", d);
}
本帖最后由 songbai220 于 2020-7-27 15:44 编辑
输出缓冲区需要预留
#include<stdio.h>
#include<stdlib.h>
int main()
{
int num;
char *c = "abcde";
//输出缓冲区
char d={0};
FILE *fp;
fp = fopen("zuihou.txt","w");
if(fp == NULL)
{
printf("内存分配失败!");
exit(0);
}
fputs(c,fp);
fclose(fp);
fp = fopen("zuihou.txt","r");
fgets(d,6,fp);
fclose(fp);
printf("%s",d);
}
页:
[1]