text 使用fopen()打开文件,使用fclose()关闭文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 使用fopen()打开文件,使用fclose()关闭文件相关的知识,希望对你有一定的参考价值。

The file manipulation functions all live in <stdio.h>. "printf()" is in <stdio.h> so most of the times we will include <stdio.h> anyway. 

When we want to work with FILE, we first have to open up a file. And the function we use for opening a file is "fopen()".  When we open up a file using "fopen()", a pointer will be created to point to the file, that is to tell the memory address where that file is stored in the memory.

So "fopen()" will open a file and return a file pointer to it. 
* It's important to always check the return value to make sure you don't get back NULL. That's the same as using pointers.

So we use the "fopen()" function like this:

FILE* ptr = fopen(<filename>, <operation>);

FILE* ptr = fopen("file1.txt", "r"); // This opens up a file named "file1.txt", and "r" means this file is only used for reading data from the file "file1.txt".

FILE* ptr = fopen("file2.txt", "w"); // This will open the file "file2.txt" for writing data into this file only. With the "w" it will start writing from the beginning of the file. If there were already data in the file, it will all be overwrited.

FILE* ptr = fopen("file3.txt", "a"); // This also opens up the file "file3.txt" and writes data into it. The difference from "w" is, this is for "appending". It will start writing from the end of previous data in the file. So no previous data in the file will be lost.


fclose() is the function used for closing the file, means we've finished doing things with the file, and now we need to close it.

fclose(<file pointer>);

Simply put the file pointer in the bracket to close the file:

fclose(ptr);

以上是关于text 使用fopen()打开文件,使用fclose()关闭文件的主要内容,如果未能解决你的问题,请参考以下文章

PHP中fopen函数的问题

文件的打开函数第一类--fopen()

无法使用模式 r 打开:fopen():AWS Elastic Beanstalk

在 FORTRAN / MPI / HDF5 ( 1.10.1 ) 中使用 h5fopen_f 打开文件时出错

c语言fopen函数 fp=fopen(" /","r") fopen 函数怎么样打开url 文件 比如 http://10.4.64.

文件操作