【发布时间】:2018-01-27 21:23:51
【问题描述】:
我想使用fwrite 函数将句子写入文本文件。所以我必须将这些作为函数参数:
fwrite( const void *restrict buffer, size_t size, size_t count, FILE *restrict stream )
- 缓冲区 - 指向要写入的数组中第一个对象的指针
- size - 每个对象的大小
- count - 要写入的对象数
- 流 - 指向输出流的指针
正如How to dynamically allocate memory space for a string and get that string from user? 所说,浪费内存是一种不好的做法。我阅读了答案并有了一个想法,以我的方式编写代码。
我的想法是:
- 创建一个字符数组并写入其元素
- 使用
malloc和realloc使该数组越来越大 - 继续写入直到到达
EOF
不幸的是,我遇到了一个问题。每当我构建和执行代码时,它都会给我这个错误:
已停止工作
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t index=0,size=1;
char ch;
FILE *fptr;
fptr=fopen("E:\\Textsample.txt","w");
/////////////////Checking///////////////
if(fptr==NULL)
{
free(fptr);
puts("Error occured!\n");
exit(EXIT_FAILURE);
}
/////////////////Checking///////////////
char *sentence =(char*) malloc(sizeof(char)) ;
puts("Plaese write :\n");
while((ch=getchar()) != EOF)
{
sentence[index]=ch;
index++;
size++;
realloc(sentence,size);
/////////////////Checking///////////////
if(sentence==NULL)
{
printf("Error Occured!\n");
free(sentence);
exit(EXIT_FAILURE);
}
/////////////////Checking///////////////
}
//Copying sentnce(s) to the text file.
fwrite(sentence,sizeof sentence[0],index,fptr);
free(sentence);
free(fptr);
return 0;
}
【问题讨论】:
-
Nitpick:您不需要在检查代码中释放 NULL ptr..
-
“已停止工作”?什么?也许在调试器中运行,看看它在哪一行崩溃。
-
另外,最后做
close(ptr),因为它是FILE *。无需免费,由fclose处理 -
getchar()返回int而不是char,这对于成功检测到EOF很重要。 -
sentence[0]是一个char,所以这个sizeof sentence[0]的大小等于char的大小,总是1。
标签: c file fwrite dynamic-allocation