虽然是c语言中的基础问题,但是自己一直没有彻底的掌握
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
void main()
{
char *s = "1234\n";
printf("%s\n",s);
write(STDOUT_FILENO, s, 4);
write(STDOUT_FILENO, s, 5);
write(STDOUT_FILENO, s, 6);
write(STDOUT_FILENO, s, 7);
int fd = creat("./test.txt", O_WRONLY|O_CREAT|O_APPEND);
if(fd < 0)
perror("create error\n");
write(fd, s, strlen(s));
write(fd, s, 4);
write(fd, s, 5);
write(fd, s, 6);
write(fd, s, 7);
}
终端输出:
1234
12341234
1234
1234
文件输出:
1234
12341234
1234
^@1234
^@.
从中我们可以看出,所谓的字符串结束符其实是对于字符串本身而言,和我们的终端或者文件无关,而且终端默认显示‘\0’为空白,但是文件显示乱码
我们再看以下几个东西:
"0":不用说
'\0':字符串结束符 ascii 0
NULL:ascii 0
'\r' :回车符 ascii 13
'\n':换行符 ascii 10
‘0’:字符0 ascii 48
例如:
void main()
{
printf("%d\n",'\r');
printf("%d\n",'\n');
printf("%c\n",'\0');
printf("%d\n",'\0');
printf("%d\n",*(int *)NULL);
}
终端输出:
13
10
0
段错误(核心已转储)
虽然NULL和'\0'的ascii都等于0, 但是两者是不同的,NULL一般用在指针,''\0一般应在数组
永远不要输出值为NULL的变量
例如:char s[10] = {0};
char *s = NULL;