如何使用系统调用 write() 输出到文件(写入文件)

How Can I use the system call write() to output to a file (write to a file)?

本文关键字:文件 何使用 输出 系统调用 write      更新时间:2023-10-16

所以我正在学习操作系统课程,现在我正在学习如何进行系统调用。所以基本上,我想将输入文件 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