gpt4 book ai didi

c++ - 尝试使用模式为 "a+"的 fwrite() 将新文本附加到现有文件,但写入了奇怪的字符串

转载 作者:行者123 更新时间:2023-11-28 05:41:54 27 4
gpt4 key购买 nike

我正在编写一个程序,每次调用时都会将文本插入到文件中。我不想重写整个文件,我希望新文本可以插入到新行中。这是我的测试代码:

void writeFile()
{
FILE *pFile;
char* data = "hahaha";
int data_size = 7;
int count = 1;
pFile = fopen("textfile.bin","a+");
if (pFile!=NULL)
{
fwrite (data, data_size, count, pFile);
fclose (pFile);
}
}

第一次调用时,一切正常。新建了一个文件,数据写入成功。但是当我再次调用它并期望插入新数据时,我在文件中得到了奇怪的字符串,例如:怜惜栀桡桡a。

我不太熟悉 C++ I/O 函数。有人可以告诉我我做错了什么吗?另外,对于将文本附加到下一行有什么建议吗?

最佳答案

我认为您遇到了代码集问题,您用来查看您编写的文件的程序希望在文件中找到 UTF-16 数据。

我基于对您引用的字符串的分析:

慨慨慨栀桡桡a

当该 (UTF-8) 数据转换为 Unicode 值时,我得到:

0xE6 0x85 0xA8 = U+6168
0xE6 0x85 0xA8 = U+6168
0xE6 0x85 0xA8 = U+6168
0xE6 0xA0 0x80 = U+6800
0xE6 0xA1 0xA1 = U+6861
0xE6 0xA1 0xA1 = U+6861
0x61 = U+0061
0x0A = U+000A

Unicode 值 U+6168 以小端字节序表示为字节 0x68 0x61,h 的 ASCII 码为 104 (0x68),a 为 97 (0x61)。因此,数据可能写入正确,但对写入数据的解释不正确。

正如我在 comment 中指出的那样:

If you want lines in the file, you'll need to put them there (by adding newlines to the data that is written), because fwrite() won't output any newlines unless they are in the data it is given to write. You have written a null byte to the file (because you used data_size = 7), which means the file is not really a text file (text files don't contain null bytes). What happens next depends on the code set you're using.

输出中出现尾随单字节代码,因为第二个空字节在此页面上粘贴的内容中不可见,而尾随 U+000A 是由命令中的 echo 添加的我用于分析的行(其中 utf8-unicode 是我编写的程序):

 echo "慨慨慨栀桡桡a" | utf8-unicode

关于c++ - 尝试使用模式为 "a+"的 fwrite() 将新文本附加到现有文件,但写入了奇怪的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36927261/

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