【问题标题】:How Can I use the system call write() to output to a file (write to a file)?如何使用系统调用 write() 输出到文件(写入文件)?
【发布时间】: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


【解决方案1】:

您对write() 的使用不正确:

        n_char=write(argv[2],buffer,n_char);

第一个参数应该是文件描述符,所以使用outFile 代替argv[2] 中的文件名。

顺便说一句,在尝试执行任何文件 i/o 之前,您应该养成验证打开是否成功的习惯。你为inFile做得很好,也为outFile做这件事

【讨论】:

  • 我修复了这个问题,但仍然找不到我的文件!还有一件事,我想显示输出文件 argv[2] 的名称。我该怎么做?所以我想打印输出文件 printf("The is the status of %d\n", argv[2]);这给我打印了一个数字而不是文件名?
  • 对于打印,将 %d 替换为 %s(请参阅here 了解 printf() 中的格式化字符或切换到 c++ 流)。
  • 请检查您的outFile打开的结果,以确保它成功(或者如果它没有得到错误消息)
  • 好吧,实际上当我尝试对输出文件进行验证时,它告诉我不是这样的文件或目录?为什么它不只是创建运行程序时给出的输出文件?为什么要在运行程序之前创建它?
  • 我发现我只需要添加 | o_create 与 open 系统调用
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 2020-12-25
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 2013-03-22
  • 2018-12-01
相关资源
最近更新 更多