[5] Linux network programming standard IO of fopen / fclose / perror

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/zztingfeng/article/details/90573424

Standard IO Libraries

To use the standard IO library, you need to include the header file  <stdio.h> . The library for the user to create a common interface for connecting a call to the underlying system, which is developed by ANSI C standard library, portability (file IO is a Unix-based POSIX standard, not portable to Windows). The same file IO is similar, it needs to open a file in order to establish a way to access, file IO access route is through the file descriptor access route, is the standard IO stream (stream), which is implemented as a point structure FILE pointer.

Basic Operations

1 open / create file streams

FILE *fopen(const char *restrict pathname, const char *restrict mode);
第一个参数: 文件的路径
第二个参数:文件打开的模式                                  
返回值: 返回指向文件的指针,指针不为NULL是成功,指针为NULL是失败

File Open Mode:

1. "r" or "rb"            : 以只读形式打开文(文件必须存在)
2. "w" or "wb"            : 以写方式打开文件并将文件长度截为0或创建一个供写的文件 
3. "a" or "ab"            : 以写方式打开文件并将内容写到文件末或创建一个文件
4. "r+" or "rb+" or "r+b" : 以更新的方式(读/写)打开文件(文件必须存在)
5. "w+" or "wb+" or "w+b" : 以更新的方式(读/写)打开文件并将文件长度截为0或创建一个文件
6. "a+" or "ab+" or "a+b" : 以更新的方式(读/写)打开文件并将更新内容写到文件末或创建一个文件

2 Close the file stream

int fclose(FILE *stream);
参数:FILE *stream: 指向被关闭文件的指针 
返回值:关闭文件成功返回0,关闭文件失败返回而EOF

3 Error Handling

IO error occurred while executing a standard function, error code will save in error, the programmer can print an error message through the appropriate function.

#include<stdio.h>
void perror(const char* s);
参数:在标准错误流上输出的信息
返回值:无

Code:

#include <stdio.h>
int main(int argc, char *argv[])
{
    FILE *fp;
	if((fp = fopen("1.txt","r")) == NULL)
	{
		perror("fail to fopen");
		return -1;
	}
    fclose(fp);   
    return 0; 
}

File does not exist, the following error will be reported:

4 strerror function

#include<string.h>
#include<errno.h>
char *strerror(int errnum);
参数:错误码
返回值:错误码对应的错误信息

Code:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    FILE *fp;
	int errno;
	if((fp = fopen("1.txt","r")) == NULL)
	{
		printf("fail to fopen:%s\n",strerror(errno));
		return -1;
	}
    fclose(fp);   
    return 0; 
}

gcc The results:

Guess you like

Origin blog.csdn.net/zztingfeng/article/details/90573424