Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

File Operation open, fopen and freopen of Cracket + under Linux

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Open is the underlying system call function under linux, and the standard Icano library function with input / output buffering under fopen and freopen cplink +.

Fopen under linxu is the encapsulated function of open, and fopen finally has to call the underlying system call open.

So if you need to have explicit control over the device under linux, you'd better use the underlying system call (open).

The corresponding file operations of open are: close, read, write,ioctl and so on.

The corresponding file operations of fopen are: fclose, fread, fwrite, freopen, fseek, ftell, rewind and so on.

A function used by freopen to redirect the input and output stream, which can change the input and output environment without changing the original appearance of the code, but should be used to ensure that the stream is reliable. See part 3 for details.

-

The difference between open and fopen:

Read fread is buffered, but not buffered.

2 open fopen is defined in standard c and force is defined in POSIX.

There is no difference between reading binary and ordinary files in linux/unix.

4. Force fopen cannot specify permissions to create files. Open can specify permissions.

Open returns the file pointer and the open returns the file descriptor (integer).

6 any device in Linux Unix is a file, and you can use open,read.

-

1. Open system call (linux)

Need to include header file: # include

# include

# include

Function prototype: int open (const char * pathname, int oflags)

Int open (const char * pathname,int oflags, mode_t mode)

Mode is used only when creating a new file and is used to specify access to the file.

Pathname is the pathname of the file to be opened / created

Oflags is used to specify the open / create mode of the file, which can be logically or composed of the following constants (defined in fcntl.h).

O_RDONLY read-only mode

O_WRONLY write-only mode

O_RDWR read-write mode

The above three are mutually exclusive, that is, they cannot be used at the same time.

When opening / creating a file, you must use at least one of the above three constants. The following constants are selected:

O_APPEND writes to the end of the file every time it writes

O_CREAT creates the specified file if it does not exist

O_EXCL returns-1 if the file you want to create already exists and modifies the value of errno

O_TRUNC if the file exists and is opened as write-only / read-write, the entire contents of the file are cleared

O_NOCTTY if the pathname points to an end device, do not use this device as a control terminal.

O_NONBLOCK if the pathname points to the FIFO/ block file / character file, the opening of the file and the subsequent Istroke O are set to non-blocking mode (nonblocking mode).

/ / the following is used to synchronize input and output

O_DSYNC waits for the physical Imax O to finish before write. Do not wait for file properties to be updated without affecting the reading of newly written data.

O_RSYNC read waits for all writes to the same area to be completed before proceeding.

O_SYNC waits for physical iThano to finish before write, including those that update file attributes.

When you use an open call with the O_CREAT flag to create a file, you must use an open call with three parameters. The third parameter, mode, is obtained by bit or after several flags.

These flags are defined in the header file sys/stat.h, as follows:

S_IRUSR: read permission, file owner

S_IWUSR: write permission, file owner

S_IXUSR: execute permission, file owner

S_IRGRP: read permission, group to which the file belongs

S_IWGRP: write permission, group to which the file belongs

S_IXGRP: execute permission, group to which the file belongs

S_IROTH: read permission, other users

S_IWOTH: write permission, other users

S_IXOTH: execute permission, other users

Return value: a file descriptor is returned if successful, otherwise-1 is returned. Returns the file descriptor (integer variable 0,255). The file descriptor returned by open must be the smallest descriptor that has not yet been used by the process. Returns-1 as long as one permission is prohibited.

Error code: (it all begins with E, and removing it is a word or an abbreviation of a word about the error)

The file referred to by the EEXIST parameter pathname already exists, but the O_CREAT and O_EXCL flags are used.

The file referred to in the EACCESS parameter pathname does not meet the permissions required for the test.

The file for which EROFS wants to test write permissions exists in a read-only file system.

The EFAULT parameter pathname pointer exceeds the accessible memory space.

The EINVAL parameter mode is incorrect.

The ENAMETOOLONG parameter pathname is too long.

The ENOTDIR parameter pathname is not a directory.

The ENOMEM core is out of memory.

The ELOOP parameter pathname has too many symbolic connection problems.

EIO I got O access error.

-

Ssize_t write (int fd, const void * buf, size_t count)

Parameters:

Fd: the file descriptor to write to.

Buf: buffer that requires output

Count: maximum output byte count

Return value: successfully returns the number of bytes written, error returns-1 and sets errno

-.

Ssize_t read (int fd, void * buf, size_t count)

Parameters:

Buf: buffer to be read

Count: maximum read byte count

Return value: successfully returns the number of bytes read, error returns-1 and sets errno. If the end of the file is reached before calling read, read returns 0 this time.

-

2. Fopen library function

Header file:

Function prototype: FILE * fopen (const char * path, const char * mode)

The path string contains the file path and file name to be opened, and the parameter mode string represents the flow pattern.

Mode has the following morphological strings:

"r" or "rb" opens the file as read-only. The file must exist.

"w" or "wb" opens the file in write mode and truncates the file length to zero.

"a" or "ab" opens the file in write mode, and the new content is appended to the end of the file.

"r +" or "rb+" or "rbinb" is opened (read and write) in an updated manner

"w +" or "wb+" or "wimpb" is opened as an update and the file length is truncated to zero.

"a +" or "ab+" or "aqb" is opened as an update, and the new content is appended to the end of the file.

The letter b indicates that a file is a binary file rather than a text file. (binary files and text files are not distinguished under linux)

Return value: after the file is opened smoothly, the file pointer to the stream will be returned. If the file fails to open, return NULL and store the error code in errno.

-

Fread is a function. Read data from a file stream, reading up to count elements, each element size bytes. If the call is successful, return the actual number of elements read, or return 0 if it is unsuccessful or read to the end of the file.

Function prototype: size_t fread (void * buffer, size_t size, size_t count, FILE * stream)

Parameters:

Buffer: the memory address used to receive data

Size: the number of bytes to read and write, in bytes

Count: how many size bytes of data items to read and write, each element is size bytes.

Stream: input stream

Return value: the number of elements actually read. If the return value is different from count, there may be an error at the end of the file, get the error message from ferror and feof, or detect whether the end of the file has been reached.

-

Fwrite: write a block to a file

Function prototype: size_t fwrite (const void* buffer, size_t size, size_t count, FILE* stream)

Parameters:

Buffer: is a pointer. For fwrite, it is the address to get the data.

Size: the number of bytes to write to

Count: the number of data items to write size bytes

Stream: target file pointer

Return value: returns the number of blocks actually written

-

Fflush: write out all the data in the file stream immediately for writing out.

Function prototype: int fflush (FILE * stream)

-

Fseek: the file stream function corresponding to the lseek system call. It specifies the location in the file stream for the next read and write operation.

Function prototype: int fseek (FILE * stream, long offset, int fromwhere)

Parameter stream is the file pointer

Parameter offset is offset, positive number indicates positive offset, negative number indicates negative offset

Parameter fromwhere sets where the offset starts in the file. Possible values are: SEEK_CUR, SEEK_END, or SEEK_SET.

SEEK_SET: the beginning of the file

SEEK_CUR: current location

SEEK_END: end of file

Among them, SEEK_SET,SEEK_CUR and SEEK_END are 0BI 1 and 2.

Return value: if the execution is successful, stream will point to the position of offset offset (pointer offset) bytes based on fromwhere, and the function will return 0. If the execution fails (for example, offset exceeds the size of the file itself), the function returns a non-zero value without changing the location where stream points.

-

The following is linux's next program to open a file and display its contents:

# include # include charchar * FILE_NAME = "/ home/hzg/uart/download.bin"; unsigned char file_buffer [20]; int main () {FILEFILE * file_fd; int read_len, I; file_fd = fopen (FILE_NAME, "rb"); if (file_fd = = NULL) {perror ("errno") } else {printf ("File Open successed!\ n");} while (1) {read_len = fread (file_buffer, 1,16, file_fd); if (read_len = =-1) {printf ("File read error!\ n"); perror ("errno") Exit (0);} else if (read_len = = 0) {printf ("File read Over!\ n"); break;} else {printf ("Read% d Byte From download.bin:", read_len); for (I = 0; I

< read_len; i++) { printf(" x",file_buffer[i]); } printf("\n"); } usleep(20000); } fclose(file_fd); return 0; } 3、freopen 函数原型:FILE * freopen ( const char * filename, const char * mode, FILE * stream ); 参数: filename: 要打开的文件名 mode: 文件打开的模式,和fopen中的模式(r/w)相同 stream: 文件指针,通常使用标准流文件(stdin/stdout/stderr) 返回值:如果成功则返回该指向该stream的指针,否则为NULL。 作用:用于重定向输入输出流的函数,将stream中的标准输入、输出、错误或者文件流重定向为filename文件中的内容。linux下需要重定向输出很容易使用 ./程序名 >

Test (> > test append), freopen can be used for input and output redirection under windows.

How to use it: because the file pointer uses a standard stream file, we can not define the file pointer.

We use the freopen () function to open the input file test.in, freopen ("test.in", "r", stdin) in read-only mode r (read).

In this way, the input of the program is converted from the standard input stream stdin to the input from the file "test.in"

Then use the freopen () function to open the output file test.out,freopen ("test.out", "w", stdout) in write mode w (write)

The output of the program will be written to the file "test.out" from the original standard output.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report