Linux C 学习日记(一)

这个学期学了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>.具体代码就不细作分析




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值