将Read缓冲区内容存储在字符串中

时间:2013-11-14 01:31:46

标签: c string io

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

到目前为止,这会写出一些奇怪的字符,并且会在额外的时间内写出内容行 如果内容超过1024,我需要继续读取所以我假设我写了如果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); 

1 个答案:

答案 0 :(得分:2)

您正在泄漏内存并超越缓冲区。这不酷。您的data数组是固定大小的:strcat不会使其变大。并且您不能保证缓冲区以空值终止,因此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在缓冲区之间复制数据。