[英]Linux Files Management
我正在學習Linux,我需要制作一個函數,使我能夠輸入重定向(stdin)和輸出重定向(stdout)。 我發現了一個示例,其中實際上創建了一個具有我選擇調用的名稱的文件文本。 但是我不明白在創建同一個文件后如何寫該文件。 我發現的功能如下
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define LOCKFILE "/etc/ptmp"
int main()
{
int pfd;
char filename[1024];
if ((pfd = open("Test", O_WRONLY | O_CREAT | O_TRUNC,S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
perror("Cannot open output file\n"); exit(1);
}
}
我需要創建一個函數,該函數允許我使用open以及dup / dup2來輸入重定向(stdin)和輸出重定向(stdout),但是我在各處搜索,找不到真正理解的答案。
所以現在我正在嘗試這種方式,但仍然無法寫入文件
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define LOCKFILE "/etc/ptmp"
int main()
{
int pfd;
char filename[1024];
if ((pfd = open("Test", O_RDONLY | O_CREAT | O_TRUNC,S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
perror("Cannot open output file\n"); exit(1);
}
dup2(STDIN_FILENO, pfd);
close(pfd);
printf("This will be put in the file\n");
return 0;
}
打開文件后,可以使用dup2()
將標准文件描述符重定向到該文件:
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define LOCKFILE "/etc/ptmp"
int main()
{
int pfd;
char filename[1024];
if ((pfd = open("Test", O_WRONLY | O_CREAT | O_TRUNC,S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
perror("Cannot open output file\n"); exit(1);
}
dup2(STDOUT_FILENO, pfd);
close(pfd);
printf("This will be put in the file\n");
return 0;
}
要重定向stdin
,請以O_RDONLY
模式打開文件,然后使用STDIN_FILENO
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.