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

标签 c++ c file-io operating-system system-calls

所以我正在学习操作系统类(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/

相关文章:

c# - 异步打开读取

c++ - 使用 getline : C++ 读取文件并在屏幕上显示

c - 动态分配的数组的大小是否存储在 RAM 中的某个位置?

c++ - 根据 C++ 中的数据类型设置默认值

ios - 包含上限值的浮点模运算符

c - 如何打印字符串的字符值?

java - 从 getContent 将文件保存在 java 中,包括新行

c++ - 关于C++中的文件输入/输出和异常

c++ - 我可以通过链接此 dl 从动态库加载函数,但如果不链接此 dl,我无法在代码中使用 'dlsym' 加载它

c++ - 模板类和在 C++ 中使用带有混合参数的重载构造函数