Ladies and gentlemen, crossing, the last time we were talking about file manipulation based on file descriptors, let's go on to this example. Gossip Hugh, words return to the positive. Let's talk C chestnuts together!
Crossing, we described in detail the system calls related to file operations in the previous section. However, there are no specific examples. Our main content is to cite examples, so today we will use specific examples to illustrate if you are using system calls to manipulate files.
The operation of the file, or the use of my summary of the file operation of the three-step curve is better:
open(file_name,flags_read); //打开文件open(file_name,flags_create,mode); //创建文件write(fd,buf,SIZE*sizeof(char)); //向文件写入数据read(fd,buf,SIZE*sizeof(char)); //从文件中读取数据close(fd); //关闭文件
Crossing, I want to emphasize that file operations are prone to errors, so you must check the results of file operations. The results of each file operation are checked in our example code. Here is an example of a check, please refer to:
if(-1 == res) { printf("read data failed \n"); close(fd); return1; } else printf("read %d chars from file,they are %s \n",res,buf);
I hope you can understand the importance of checking the results of file operation from the example, and then develop good programming habits.
Crossing, the above is the core code, the complete code put in my resources, you can click here to download the use.
In the code we first create a file called Test, then write the data to the file, close the file, and release the file descriptor associated with the file. We then open the file in a read-only manner, then read the data from the file, output it to the terminal, close the file, and release the file descriptor associated with the file.
Here is the result of the program running:
write16charsintofileread16charsfromfileword
Everyone crossing, about file manipulation: Based on file descriptor examples Let's talk about this. I want to know what the following example, and listen to tell.
Talk C Chestnut Bar (140th: C Language Instance-file operation: Based on file description usable)