gpt4 book ai didi

将字符数组复制到文本文件中

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:00 26 4
gpt4 key购买 nike

我想使用 fwrite 函数将句子写入文本文件。所以我必须将这些作为函数参数:

fwrite( const void *restrict buffer, size_t size, size_t count, FILE *restrict stream )
  1. buffer - 指向数组中要写入的第一个对象的指针
  2. size - 每个对象的大小
  3. count - 要写入的对象数
  4. stream - 指向输出流的指针

作为How to dynamically allocate memory space for a string and get that string from user?说,浪费内存是一种不好的做法。我阅读了答案并产生了以我的方式编写代码的想法。

我的想法是:

  1. 制作一个字符数组并写入其元素
  2. 使用 mallocrealloc 使数组越来越大
  3. 继续写入直到到达EOF

不幸的是我遇到了一个问题。每当我构建和执行代码时,它都会给我这个错误:

has stopped working

这是我的代码:

#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;
}

最佳答案

我认为你需要写sentence = realloc(sentence, size)

此外,每次我们需要时,将分配的大小加倍会更有效。然后我们可以再次阅读我们已经阅读过的内容,因此我们需要更少的重新分配。因此 size 加倍(这是分配的缓冲区的大小,而 index 跟踪读取的字符。

所以

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
size_t index=0,size=1;
int ch;
FILE *fptr;
fptr=fopen("./bla.txt","w");

/////////////////Checking///////////////
if(fptr==NULL)
{
fprintf(stderr, "Error occured!\n");
exit(EXIT_FAILURE);
}
/////////////////Checking///////////////

char *sentence = malloc(size) ;
puts("Please write, (close with return) :\n");

while((ch=getchar()) != '\n')
{
sentence[index]=(ch & 0xff);
index++;;
if (index >= size){
sentence = realloc(sentence,2*size);

/////////////////Checking///////////////
if(sentence==NULL)
{
fclose(fptr);
fprintf(stderr, "Error Occured!\n");
free(sentence);
exit(EXIT_FAILURE);
}
/////////////////Checking///////////////
size *= 2; /* update size */
}
}

//Copying sentence(s) to the text file.
fwrite(sentence,1,index,fptr);
free(sentence);
fclose(fptr);
return 0;

这在我的系统上运行良好。

关于将字符数组复制到文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45769377/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com