📅  最后修改于: 2020-09-25 08:18:31             🧑  作者: Mango
FILE* fopen (const char* filename, const char* mode);
fopen()
函数采用两个参数,并返回与由参数filename指定的文件关联的文件流。
它在
不同类型的文件访问模式如下:
File Access Mode | Interpretation | If file exists | If file doesn’t exist |
---|---|---|---|
“r” | Opens the file in read mode | Read from start | Error |
“w” | Opens the file in write mode | Erase all the contents | Create new file |
“a” | Opens the file in append mode | Start writing from the end | Create new file |
“r+” | Opens the file in read and write mode | Read from start | Error |
“w+” | Opens the file in read and write mode | Erase all the contents | Create new file |
“a+” | Opens the file in read and write mode | Start writing from the end | Create new file |
#include
#include
using namespace std;
int main()
{
int c;
FILE *fp;
fp = fopen("file.txt", "w");
char str[20] = "Hello World!";
if (fp)
{
for(int i=0; i
当您运行该程序时,它不会生成任何输出,但是会写“ Hello World!"。到文件“ file.txt"。
#include
using namespace std;
int main()
{
int c;
FILE *fp;
fp = fopen("file.txt", "r");
if (fp)
{
while ((c = getc(fp)) != EOF)
putchar(c);
fclose(fp);
}
return 0;
}
当您运行该程序时,输出将为[假定与示例1中的文件相同]:
Hello World!
#include
#include
using namespace std;
int main()
{
int c;
FILE *fp;
fp = fopen("file.txt", "a");
char str[20] = "Hello Again.";
if (fp)
{
putc('\n',fp);
for(int i=0; i
当您运行该程序时,它将不会生成任何输出,但是会将“ Hello Again"以换行符附加到文件“ file.txt"中。