说明:
open函数:是Linux的系统函数。
close函数:是Linux的系统函数。
文件有打开(open)就要有关闭(close),文件的打开和关闭时搭配使用的。
环境:Vmware Workstation;CentOS-6.4-x86_64
文件操作:有打开,必须有关闭。
图解说明:
步骤:
1、创建并编辑main.c:
#include <stdio.h>
// 包含open所需要的头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
// 包含close所需要的头文件
#include <unistd.h>
int main(int argc, char *args[])
{
// 以只读方式打开一个文件a.txt
int fd = open("a.txt", O_RDONLY);
// 判断文件是否打开成功
if (fd == -1)
{
printf("open file failed.\n");
}
// 打开文件成功,关闭文件
close(fd);
return 0;
}
2、创建并编辑makefile文件:
.SUFFIXES:.c .o
CC=gcc
SRCS=main.c
OBJS=$(SRCS:.c=.o)
EXEC=main
start: $(OBJS)
$(CC) -o $(EXEC) $(OBJS)
@echo "-----------------------------OK-----------------------"
.c.o:
$(CC) -Wall -o $@ -c $<
clean:
rm -rf $(EXEC) $(OBJS)
3、创建文件a.txt,编译并执行程序:
[negivup@negivup mycode]$ <span style="background-color: rgb(255, 255, 153);">touch a.txt</span>
[negivup@negivup mycode]$ <span style="background-color: rgb(255, 255, 153);">make</span>
gcc -Wall -o main.o -c main.c
gcc -o main main.o
-----------------------------OK-----------------------
[negivup@negivup mycode]$ <span style="background-color: rgb(255, 255, 153);">./main</span>
说明:
操作文件的时候,一定需要打开文件,打开文件之后一定要记得关闭。
PS:根据传智播客视频学习整理得出。