我想将一个预定义的字符串数组写入file.txt,如下所示:
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
char *somestr[] = {"haha\n", "aww\n", "hmm\n", "hello\n", "there\n"};
int filedesc = open("testfile.txt", O_WRONLY | O_APPEND | O_CREAT);
for (int i = 0; i < 5; ++i) {
write(filedesc, somestr[i], 24);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这将创造testfile.txt.预期的文件内容:
haha
aww
hmm
hello
there
Run Code Online (Sandbox Code Playgroud)
但是当我尝试时,它给出了一个奇怪的结果.实际内容:
haha\00aww\00hmm\00hello\00there\00aww\00hmm\00hello\00there\00testfihmm\00hello\00there\00testfile.txhello\00there\00testfile.txt\00\00there\00testfile.txt\00\00; 4\00\00\00
您假设所有字符串的长度均为24个字符.这是不正确的.您正在边界外阅读并将其写入文件.
而是使用正确的长度.
即
write(filedesc, somestr[i], strlen(somestr[i]));
Run Code Online (Sandbox Code Playgroud)
当然添加相应的包含文件 - 可以在手册页上找到 strlen