【发布时间】:2016-05-01 00:22:12
【问题描述】:
所以我正在学习操作系统课程,现在我正在学习如何进行系统调用。所以基本上,我想将一个输入文件 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
【问题讨论】:
-
您打开“outFile”,但尝试写入“argv[2]”。那是行不通的!
-
...假设 outFIle 已打开正常 - 您必须检查所有系统调用的结果。
-
..并在完成后关闭文件以刷新它们并清理 fd。
-
@MartinJames 那么我应该使用什么来代替 argv[2],我应该自己使用 outFile 吗?关闭时,我应该说 close(inFile);关闭(outFile) ??
-
@Pro 请不要更新问题中的代码以反映答案中建议的更改 - 这会使问题没有任何意义,因为代码现在是正确的!
标签: c++ c file-io operating-system system-calls