Linux C/C++ 系统错误

在C++中,如果调用了库函数,可以通过函数的返回值判断调用是否成功。其实还有一个整型的全局变量errno,存放了函数调用过程中产生的错误代码。

如果调用库函数失败,可以通过errno的值来查找原因

复制代码
#include <errno.h>

strerror()库函数(在<string.h>中声明)

复制代码
char *strerror(int errnum);		//非线程安全
int strerror_r(int errnum,char *buf,size_t buflen);		//线程安全

gcc8.3.1版本一共有133个错误代码

举例

复制代码
#include<iostream>
#include<string.h>
#include<errno.h>
#include<sys/stat.h>
using namespace std;

int main()
{
    int iret = mkdir("/tmp/aaa",0755);

    cout<<"iret="<<iret<<endl;
    cout<<"error="<<strerror(errno)<<endl;
}

[root@localhost 06demoerror]# g++ -o demo_error demo_error.cpp 
[root@localhost 06demoerror]# ./demo_error 
iret=0
error=Success
[root@localhost 06demoerror]# ./demo_error 
iret=-1
error=File exists

perror()库函数

在<stdio.h>中声明,用于在控制台显示最近一次系统错误消息

复制代码
void perror(const char*s);

调用库函数不一定设置errno,errno不能作为调用库函数失败的标准


推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家:
零声白金学习卡(含基础架构/高性能存储/golang云原生/音视频/Linux内核)
https://xxetb.xet.tech/s/3Zqhgt

相关推荐
石像鬼₧魂石8 小时前
如何配置Fail2Ban的Jail?
linux·学习·ubuntu
hetao17338379 小时前
2025-12-12~14 hetao1733837的刷题笔记
数据结构·c++·笔记·算法
椰子今天很可爱9 小时前
五种I/O模型与多路转接
linux·c语言·c++
Lueeee.9 小时前
Linux kernel Makefile 语法
linux
程序员zgh9 小时前
C++ 互斥锁、读写锁、原子操作、条件变量
c语言·开发语言·jvm·c++
喵了meme10 小时前
C语言实战5
c语言·开发语言
爱吃山竹的大肚肚11 小时前
EasyPOI 大数据导出
java·linux·windows
极地星光11 小时前
dmesg 工具的核心功能与作用
linux
獭.獭.11 小时前
C++ -- STL【unordered_set和unordered_map的使用】
c++·stl·unordered_map·unordered_set
神仙别闹12 小时前
基于C语言实现B树存储的图书管理系统
c语言·前端·b树