为什么我不能从我写文本的文件中读取数据。 C
Why can't I read data from file where i wrote text. C
我是 C 的新手,所以我有点困惑。这是我的代码:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>
#define FILENAME "/var/note"
int main(int argc, char *argv[])
{
int userid = getuid();
int fd = open(FILENAME, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);
write(fd, &userid, 4);
}
基本上我是在文本文件中写入 UID。但是当我尝试实际打开笔记文件(用手)时,它给我错误提示:
The file you opened has some invalid characters. If you continue editing this file you could corrupt this document.
You can also choose another character encoding and try again.
我不明白为什么它会给我这个错误(当我实际上在这个文件中写了一些文本时)以及如何解决它。在我看来,问题出在字符编码上,但我不知道该使用哪一个。对不起,如果问题听起来很愚蠢。谢谢。
write(fd, &userid, 4);
您正在从 userid
变量开头的内存中写入 4 个字节的数据,该变量是 int
.
假设您的用户 ID 是 42
,您的 LSB is on the right (in human reading order) and your architecture is in Big endian。您的变量包含这 4 个字节:
0000 0000 0000 0000 0000 0000 0010 1010
您正在文件中写入这 4 个字节,这导致这些字符:
NUL NUL NUL *
你的记事本警告你,因为文件中有 NUL
是不正常的(提醒:这是为 guid 42 编写的,YMMV)
我是 C 的新手,所以我有点困惑。这是我的代码:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>
#define FILENAME "/var/note"
int main(int argc, char *argv[])
{
int userid = getuid();
int fd = open(FILENAME, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);
write(fd, &userid, 4);
}
基本上我是在文本文件中写入 UID。但是当我尝试实际打开笔记文件(用手)时,它给我错误提示:
The file you opened has some invalid characters. If you continue editing this file you could corrupt this document. You can also choose another character encoding and try again.
我不明白为什么它会给我这个错误(当我实际上在这个文件中写了一些文本时)以及如何解决它。在我看来,问题出在字符编码上,但我不知道该使用哪一个。对不起,如果问题听起来很愚蠢。谢谢。
write(fd, &userid, 4);
您正在从 userid
变量开头的内存中写入 4 个字节的数据,该变量是 int
.
假设您的用户 ID 是 42
,您的 LSB is on the right (in human reading order) and your architecture is in Big endian。您的变量包含这 4 个字节:
0000 0000 0000 0000 0000 0000 0010 1010
您正在文件中写入这 4 个字节,这导致这些字符:
NUL NUL NUL *
你的记事本警告你,因为文件中有 NUL
是不正常的(提醒:这是为 guid 42 编写的,YMMV)