我是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;
}
答案 0 :(得分:2)
c++ has its own输入/输出操作,对于输出,标准为std::cout
。
但是c中的函数名write
以及使用文件描述符的write
:int
这是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 功能
因此,根据您编码的级别,您应该决定使用哪种功能最适合您。我认为c++程序员不会将这些级别用于标准c++代码。
system-called
所在位置的简单屏幕截图。