如何在C ++中使用write()系统调用?

时间:2017-09-08 12:36:55

标签: c++

我是C ++的初学者,我想知道如何在C ++中使用write()系统调用,而不是使用cout来获取成功和错误消息。

#include <iostream>
#include <stdio.h>
using namespace std;

int rename(const char *oldpath, const char *newpath);

int main()
{
  int result;
  char oldpath[] = "oldfile.cpp";
  char newpath[] = "newfile.cpp";
  result = rename(oldpath, newpath);

  if (result == 0)
    {
      cout << "File renamed successfully\n";
    }
 else
    {
      cout << "Error renaming the file\n";
    }
  return 0;
}

1 个答案:

答案 0 :(得分:2)

has its own输入/输出操作,对于输出,标准为std::cout
但是中的函数名write以及使用文件描述符writeint

这是man 2 write

WRITE(2)                            Linux Programmer's Manual                            WRITE(2)

NAME
       write - write to a file descriptor

SYNOPSIS
       #include <unistd.h>

       ssize_t write(int fd, const void *buf, size_t count);

系统调用Linux Kernel中实施 并且用户无权访问它。但像standard C library或类似GNU C library这样的库会包含其他人可以轻松使用的系统调用。

请参阅此页:https://www.kernel.org/doc/man-pages/

然后转到
2:System calls记录Linux内核提供的系统调用。

然后在底部你会找到write(2)

一个简单的例子是:

int fd = open( "file", O_RDONLY );
if( fd == -1 )
{
    perror( "open()" );
    close( fd );
    exit( 1 );
}

char buffer[ 100 ];
ssize_t read_byte;

if( ( read_byte = read( fd, buffer, 100 ) ) == -1 )
{
    perror( "read()" );
    close( fd );
    exit( 1 );
}

if( write( STDOUT_FILENO, buffer, read_byte ) == -1 )
{
    perror( "write()" );
    close( fd );
    exit( 1 );
}

close( fd );

你也应该使用这个头文件:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <stdlib.h>   // exit()
#include <stdio.h>    // for perror()

这些功能也称为低级I / O 功能

因此,根据您编码的级别,您应该决定使用哪种功能最适合您。我认为程序员不会将这些级别用于标准代码。

system-called所在位置的简单屏幕截图。

system-call

source