gpt4 book ai didi

c++ - 从未知长度的缓冲区中读取 CString?

转载 作者:行者123 更新时间:2023-11-30 04:16:19 28 4
gpt4 key购买 nike

假设我有一个文件。我将所有字节读入一个无符号字符缓冲区。从那里我试图在不知道它的长度的情况下读取一个 c 字符串(空终止)。

我尝试了以下方法:

char* Stream::ReadCString()
{
char str[0x10000];
int len = 0;
char* pos = (char*)(this->buffer[this->position]);
while(*pos != 0)
str[len++] = *pos++;
this->position += len+ 1;
return str;
}

我想我可以在遍历时填充 str 数组中的每个字符,检查该字符是否以 null 终止。这是行不通的。有帮助吗?

this->buffer = 字节数组
this->position = 数组中的位置

还有其他方法吗?我想我可以通过实际缓冲区的地址来运行它:str[len++] = *(char*)(this->buffer[this->position++]) ?

更新:我的新功能:

char* Stream::ReadCString()
{
this->AdvPosition(strlen((char*)&(this->buffer[this->position])) + 1);
return (char*)&(this->buffer[this->position]);
}

并调用它:

printf( "String: %s\n", s.ReadCString()); //tried casting to char* as well just outputs blank string

示例文件: enter image description here

最佳答案

检查这个:

#include <cstring>
#include <iostream>

class A
{
unsigned char buffer[4096];
int position;

public:
A() : position(0)
{
memset(buffer, 0, 4096);
char *pos = reinterpret_cast<char*>(&(this->buffer[50]));
strcpy(pos, "String");
pos = reinterpret_cast<char*>(&(this->buffer[100]));
strcpy(pos, "An other string");
}

const char *ReadString()
{
if (this->position != 4096)
{
while (std::isalpha(this->buffer[this->position]) == false && this->position != 4096)
this->position++;
if (this->position == 4096)
return 0;
void *tmp = &(this->buffer[this->position]);
char *str = static_cast<char *>(tmp);
this->position += strlen(str);
return (str);
}
return 0;
}

};

reintrepret_cast 仅用于初始化,因为您正在从文件中读取

int     main()
{
A test;

std::cout << test.ReadString() << std::endl;
std::cout << test.ReadString() << std::endl;
std::cout << test.ReadString() << std::endl;
}

http://ideone.com/LcPdFD

编辑我已经改完 ReadString()

关于c++ - 从未知长度的缓冲区中读取 CString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17804295/

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