-01
1.项目需求
2.大致分析
3.推荐参考书目
-
man 手册
-
UNIX环境高级编程
-
UNIX网络编程
-
TCP/IP详解(卷一)
-
深入理解计算机系统
man 手册,一个学习的帮助手册 如果linux上没有没有man手册,则使用一下命令进行下载
sudo yum -y install man-pages
如何使用 man 手册,直接使用命令 man 需要查的函数名
例如你 fopen 这个函数不知道如何使用, 直接 man fopen,
再例如 你不知道 socket 是什么 直接 man socket会告诉你 它是干嘛的头文件是啥,哪个函数可以调用
使用man 手册 中的查到的函数时一定要包它提示的头文件,有多少包多少
4. IO : 标准io 比系统调用io 的可移植性性强,标准io 有buffer, 系统调用io 没有buffer
只有 r 和 r+要求 文件存在,不然会报错
perror
我遇到的问题: 我输入man perror 竟然是我的mysql的perror
这里犯了一个低级的错误,之后才发现的,man 使用错了,perror 在标准库,第3章节,应该 man 3 perror
man的使用
另一个好用的:strerror
使用 strerror
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main()
{
FILE * fp;
fp = fopen("tmp","r");
if(fp==NULL)
{
fprintf(stderr,"fopen()%d\n",strerror(errno));
exit(1);
}
puts("Ok!");
exit(0);
}
一个文件最多能被打开多少次
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main()
{
FILE * fp=NULL;
int count=0;
while(1){
fp = fopen("/usr/local/c_study/tmp","r");
if(fp==NULL)
{
fprintf(stderr,"fopen()%d\n",strerror(errno));
//exit(1);
break;
}
count++;
}
//puts("Ok!");
printf("count=%d\n",count);
5.写一个拷贝命令
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
FILE * fps,*fpd;
int ch;
fps=fopen(argv[1],"r");
if(fps==NULL)
{
perror("fopen()");
exit(1);
}
fpd=fopen(argv[2],"w");
if(fpd==NULL)
{
perror("fopen()");
exit(1);
}
while(1){
ch=fgetc(fps);//读,读一次写一次
if(ch==EOF)
break;
fputc(ch,fpd);//写
}
fclose(fpd);
fclose(fps);
}
使用这个命令
加入没有目标文件,只有拷贝的源文件则会报错但又要提醒用户,在int ch;之后加入下面几行代码,即可提示用户
if(argc<3)
{
fprintf(stderr,"Uage:%s <src_file> <dest_file>\n",argv[0]);
}
效果
防止泄露
6.写一个统计文件字数的 命令 count
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
FILE * fps;
int count=0;
if(argc<2)
{
fprintf(stderr,"Uage:%s <fileName>\n",argv[0]);
}
fps=fopen(argv[1],"r");
if(fps==NULL)
{
perror("fopen()");
exit(1);
}
while(fgetc(fps)!=EOF)
{
count++;
}
printf("The Size of the File is: %d\n",count);
fclose(fps);
}
效果:
如有错误,欢迎批评,谢谢!