宏assert
显然它的原型定义在头文件<assert.h>中
assert的使用
void ASSERT(int* p,int n)
{
assert(p);
for (int i = 0; i < n; i++)
{
*(p + i) = i;
printf("%d", *(p + i));
}
}
宏assert经常于函数的开始处检验传入的参数的合法性,可以将其看作是异常处理的高级形势。
assert 的作用是先计算表达式 expression,然后判断:
1.如果表达式值为假,那么它先向 stderr 打印错误信息,然后通过调用 abort 来终止程序运行
2.如果表达式值为真,继续运行后面的程序。
注意
assert 只在 DEBUG 下生效,在调试结束后,可以通过在 #include <assert.h> 语句之前插入 #define NDEBUG 来禁用 assert 调用。
函数sprintf和sscanf
struct S
{
int a;
char b;
char c[20];
};
void fff(void)
{
struct S s = { 2,'b',"just so so!" };
char buf[100] = { 0 };
sprintf(buf, "%d %c %s", s.a, s.b, s.c);
printf(buf);
}
int main()
{
fff();
return 0;
}
sprintf的作用是将一种类型转化成字符串,但不会打印
struct S
{
int a;
char b;
char c[20];
};
void fff(void)
{
struct S s = { 2,'b',"just so so!" };
char buf[100] = { 0 };
sprintf(buf, "%d %c %s", s.a, s.b, s.c);
printf(buf);
struct S temp = { 0 };
sscanf(buf, "%d %c %s", &(temp.a), &(temp.b), temp.c);
printf("%d %c %s", temp.a, temp.b, temp.c);
}
int main()
{
fff();
return 0;
}
sscanf的作用是将一个字符串转化成一种类型
这个printf不能打印出空格,遇到空格和\0都会停止
函数strerror和perror
void f(void)
{
char ch = 0 ;
FILE* fp = fopen("test.txt", "r");
if (fp == NULL)
{
perror("fopen:");
perror("");
return 1;
}
ch = fgetc(fp);
printf("%c", ch);
fclose(fp);
fp = NULL;
}
因为test.txt文件不存在,此函数就会打印对应的错误信息
void f(void)
{
char ch = 0 ;
FILE* fp = fopen("test.txt", "r");
if (fp == NULL)
{
printf("%s\n", strerror(errno));
return;
}
ch = fgetc(fp);
printf("%c", ch);
fclose(fp);
fp = NULL;
}
strerror和perror可以达到相同的效果,但显然后者更方便
函数feof和ferror
void ff(void)
{
char ch[20] = { 0 };
FILE* fp = fopen("test.txt", "w");
if (fp == NULL)
{
perror("fopen");
return;
}
fputs("hello word!", fp);
//fgets(ch, 20, fp);
//printf("%s", ch);
if (ferror(fp))
printf("error");
else if (feof(fp))
printf("success");
fclose(fp);
fp = NULL;
}
此处的fp指针会自动向后移动
feof函数是判断文件是否是正常读取,若是则返回“真”,ferror则刚好相反
宏offsetof
#include<stdio.h>
#include<stddef.h>
struct S
{
char a;
int b;
char c;
};
#define OFFSETOF(struct_name,number_name) (int)&(((struct_name*)0)->number_name)
int main()
{
printf("%d\n", (int)offsetof(struct S,c));
printf("%d\n", OFFSETOF(struct S, c));
return 0;
}
就是用来计算结构里成员的偏移量
宏#pramga once
也可以这么写
#ifndef _TEST_H
#define _TEST_H
//头文件的内容
#endif
都可以实现防止一格文件被多次包含
可用于日志记录