这个学期学了Tcp/IP socket 编程。老师顺便讲了下Linux c的相关知识。所以在这把自己学到的东西记下来。
下面所说的是关于文件读写的。
(1)用LInux C的标准库函数实现文件的复制。先贴上代码吧。稍后再做分析。
/**
*库函数调用
**/
#include <stdio.h>
int main()
{
FILE *f1,*f2;
int c;
f1 = fopen("C:/Users/y1205_000/Desktop/a.txt","r");
f2 = fopen("C:/cygwin64/home/y1205_000/code/copy_a.txt","w");
while((c=fgetc(f1))!=EOF)
{
fputc(c,f2);
}
fclose(f1);
fclose(f2);
return 0;
}
首先创建两个文件指针,代表源文件和目的文件。这里用到了fopen(),fgetc(),fput()三个函数。通过查帮助手册可知。
FILE *fopen(const char *path, const char *mode);
这个函数用于打开文件,第一个参数代表文件的路径,第二个参数代表打开文件的模式。
关于mode参数的取值可有如下几种情况
r Open text file for reading. The stream is positioned at the //只读
beginning of the file.
r+ Open for reading and writing. The stream is positioned at the //可读可写
beginning of the file.
w Truncate file to zero length or create text file for writing. //只读
The stream is positioned at the beginning of the file.
w+ Open for reading and writing. The file is created if it does //可读可写,文件不存在时会创建文件
not exist, otherwise it is truncated. The stream is positioned
at the beginning of the file.
a Open for appending (writing at end of file). The file is cre‐//将要写的内容追加到文件末尾,文件不存在时会创建文件
ated if it does not exist. The stream is positioned at the end
of the file.
a+ Open for reading and appending (writing at end of file). The
file is created if it does not exist. The initial file position
for reading is at the beginning of the file, but output is
always appended to the end of the file.
fgetc()函数用于读取文件,返回一个int类型的值,如果读到了文件末尾或者文件存在错误则返回EOF。fput( ,)函数用于写文件,将第一个参数写到第二个参数中去.
(2)系统调用实现文件复制
/**
*使用系统调用进行读写
**/
#include <unistd.h>
#include <fcntl.h>
int main()
{
char buff[1024];
int f1,f2,n;
f1 = open("C:/cygwin64/home/y1205_000/code/copy_a.txt",O_RDONLY|O_NONBLOCK);
f2 = open("C:/Users/y1205_000/Desktop/a.txt",O_WRONLY|O_CREAT);
n = read(f1,buff,1024);
write(f2,buff,n);
return 0;
}
使用系统调用时,所用的头文件为<unistd.h>.具体代码就不细作分析