如何使用系统调用 write() 输出到文件(写入文件)
How Can I use the system call write() to output to a file (write to a file)?
所以我正在学习操作系统课程,现在我正在学习如何进行系统调用。所以基本上,我想将输入文件 openClose.in 复制到一个名为openClose.out的文件中。到目前为止,这是我的代码
#include <cstdio>
#include <unistd.h>
#include <cstdlib>
#include <sys/types.h> //needed for open
#include <sys/stat.h> //needed for open
#include <fcntl.h> //needed for open
#include <errno.h> //must use for perror
#include <grp.h>
#include <pwd.h>
using namespace std;
int main (int argc, char *argv[])
{
int inFile;
int outFile;
int n_char=0;
char buffer[32];
int fstat(int fildes, struct stat *buf);
struct stat statBuf;
struct group grp;
struct passwd pwd;
int err;
int err2;
if(argc != 3)
{
printf("Usage: openClose <infile> <outfile> n");
//return 1;
exit(1);
}
inFile=open(argv[1],O_RDONLY);
outFile=open(argv[2],O_RDWR);
if (inFile==-1)
{
printf("");
perror(argv[1]);
exit(1);
}
//Use the read system call to obtain 32 characters from inFile
while( (n_char=read(inFile, buffer, 32))!=0)
{
//Display the characters read
n_char=write(argv[2],buffer,n_char);
}
err = fstat(inFile, &statBuf);
printf("The is the status of %dn", argv[1]);
printf("File Size t Owner t Group ID t Last Modified n %d t t %d t %d t t %d n",statBuf.st_size,statBuf.st_uid,stat,statBuf.st_gid,statBuf.st_mtime);
return 0;
}
但是由于某种原因,我似乎无法让它工作,我不知道为什么我看不到输出文件。
我正在使用两个参数从终端运行我的程序,如下所示
打开(可执行) 输入文件1 输入文件2
您对write()
的使用不正确:
n_char=write(argv[2],buffer,n_char);
第一个参数应该是文件描述符,因此请使用 outFile
而不是 argv[2]
中的文件名。
顺便说一下,在尝试执行任何文件 I/O 之前,您应该养成验证打开是否成功的习惯。 你为inFile
做得很好,也为outFile
相关文章:
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 如何在其他文件中使用函数
- 在实现文件中使用头文件的通用 lambda
- 将 getline() 与文件一起使用
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 定义C++新的环境变量并在 bat 文件中使用它
- 如何在另一个 CPP 文件中使用一个 cpp 文件中的函数?
- 在 embarcadero / RAD 工作室中的 .dfm 文件中使用常量
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- 如何在 linux 可执行文件中使用静态库
- 在C++的头文件中使用常量并在程序中询问其地址的任何潜在危险
- 使用 libssh 从 SFTP 服务器下载文件并使用 C++ 将其写入 ofstream?
- CocoaPod - 在头文件中使用 C++ 时出现 Podspec 检查错误
- 链接器输入文件未使用,因为链接未完成,我无法获得.o
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 如何为文件路径使用变量?
- 没有头文件如何使用c ++调用其他模块中的函数?
- 在带有类型保护的模板文件中使用前向声明
- 无法使包含.hpp文件与其中的2个文件一起使用
- 文件删除(使用取消链接)与释放所有磁盘空间之间的延迟