我正在分析 Linux 中的 C 程序写入文件的方式,并将其总结为:
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include "restart.h"
#define CREATE_FLAGS (O_WRONLY | O_CREAT | O_APPEND)
#define CREATE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int main(void) {
int fd;
fd = open("my.file", CREATE_FLAGS, CREATE_MODE);
dup2(fd, STDOUT_FILENO);
r_close(fd) ;
write(STDOUT_FILENO, "Hello World", 11) ;
return 0;
}
两个小头文件 r_close.c 和 restart.h 在这个链接中。
所以我的问题是我想知道程序是如何写入文件的。例如,在 c# 中这样做有什么区别:
static void Main(string[] args)
{
var file = System.IO.File.OpenWrite("my.file");
file.Write(System.Text.Encoding.ASCII.GetBytes("Hello World"), 0, 11);
file.Close();
}
我在许多链接中查看了 dup2 方法的描述,例如http://www.mkssoftware.com/docs/man3/dup2.3.asp ,我很难理解它的基本功能。