所以我正在学习操作系统类(class),现在我正在学习如何进行系统调用。所以基本上,我想将输入文件 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 %d\n", 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
也做得很好
关于c++ - 如何使用系统调用 write() 输出到文件(写入文件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34979946/