- C標準庫
- C庫 - 首頁
- C庫 - <assert.h>
- C庫 - <complex.h>
- C庫 - <ctype.h>
- C庫 - <errno.h>
- C庫 - <fenv.h>
- C庫 - <float.h>
- C庫 - <inttypes.h>
- C庫 - <iso646.h>
- C庫 - <limits.h>
- C庫 - <locale.h>
- C庫 - <math.h>
- C庫 - <setjmp.h>
- C庫 - <signal.h>
- C庫 - <stdalign.h>
- C庫 - <stdarg.h>
- C庫 - <stdbool.h>
- C庫 - <stddef.h>
- C庫 - <stdio.h>
- C庫 - <stdlib.h>
- C庫 - <string.h>
- C庫 - <tgmath.h>
- C庫 - <time.h>
- C庫 - <wctype.h>
- C程式設計資源
- C程式設計 - 教程
- C - 有用資源
C庫 - abort() 函式
C 的stdlib 庫 abort() 函式允許我們透過引發 'SIGABRT' 訊號來終止或退出程式。
'SIGABRT' 訊號是作業系統中用於指示程式異常終止的訊號之一。
此函式可用於查詢嚴重錯誤、除錯或後備安全。
語法
以下是 abort() 函式的 C 庫語法:
void abort(void)
引數
此函式不接受任何引數。
返回值
此函式不返回任何值。
示例1
在這個例子中,我們建立一個基本的C程式來演示 abort() 函式的使用。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *stream;
if ((stream = fopen("D:tpwork/tutorialspoint", "r")) == NULL)
{
perror("Could not open data file");
abort();
}
return 0;
}
輸出
以下是輸出:
Could not open data file: No such file or directory
示例2
讓我們建立另一個例子,當分配的記憶體為 'NULL' 時,我們使用abort() 函式。否則列印 ptr 的值。
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int*)malloc(sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed. Aborting program.\n");
abort();
}
// If allocation was successful, use the allocated memory
*ptr = 5;
printf("Value at ptr: %d\n", *ptr);
// Free the allocated memory
free(ptr);
return 0;
}
輸出
以下是輸出:
Value at ptr: 5
示例3
在這裡,我們建立了一個C程式來開啟一個檔案。如果檔案不可用,我們將立即中止程式。
#include <stdio.h>
#include <stdlib.h>
int main () {
printf("Opening the tutorialspoint.txt\n");
FILE *fp;
// open the file
fp = fopen("tutorialspoint.txt", "r");
if (fp == NULL) {
perror("Aborting the program");
abort();
} else {
printf("File opened successfully\n");
}
printf("Close tutorialspoint.txt\n");
// close the file
fclose(fp);
return(0);
}
輸出
以下是輸出:
Opening the tutorialspoint.txt Aborting the program: No such file or directory Aborted (core dumped)
廣告