gpt4 book ai didi

c - 将读取缓冲区内容存储在字符串中

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

我试图从一个文件中读取内容,将其存储在一个字符串中,获取该字符串的长度,写入该字符串的长度,然后将文件的内容写入另一个文件。实现归档# 内容,其中 # 是内容的长度。

到目前为止,这会写出一些奇怪的字符并额外写出内容行。
如果内容超过 1024,我需要继续阅读,所以我假设我写 if len == 1024 然后再次读取并将其连接到数据。我目前还没有实现它,但希望在我开始使我的文件更大之前让它工作。

int file2p = open(curFilePath, O_RDONLY, 0);
if(file2p == -1){
printf("File open error.");
exit(1);
}
char buffer[1024];
int len;
int dataLen;
char data[1024];
while((len = read(file2p, buffer, 1024)) != 0){
if(len == -1){
printf("File open error.\n");
exit(1);
}
strcat(data, strdup(buffer));
printf("data: %s", data);
}
dataLen = strlen(data);
int lenLen = strlen(&dataLen);
write(filep, &dataLen, lenLen);
write(filep, ">", 1);
write(filep, data, dataLen);
//free(data);
close(file2p);

最佳答案

您正在泄漏内存和溢出缓冲区。这不酷。您的 data 数组是固定大小的:strcat 不会使其变大。而且您不能保证缓冲区以 null 结尾,因此 strdup 是不可能的。

你想要这样的东西:

size_t dataLen = 0;
char *data = NULL;

while( (len = read(file2p, buffer, 1024)) != 0 ){
if( len == -1 ) {
perror( "Read failed" );
exit(1);
}

data = realloc( data, dataLen + len );
if( !data ) {
printf( "Not enough contiguous memory\n" );
exit(1);
}

memcpy( &data[dataLen], buffer, len );
dataLen += len;
}

write(filep, &dataLen, sizeof(dataLen));
write(filep, ">", 1);

if( data ) {
write(filep, data, dataLen);
free(data);
}

上面的代码不是最有效的方法,只是基于您现有代码的示例。它根据需要动态分配 data 缓冲区并调整其大小,并使用 memcpy 在缓冲区之间复制数据。

关于c - 将读取缓冲区内容存储在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19967860/

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