c语言fopen函数问题

Python011

c语言fopen函数问题,第1张

fopen

函数

返回的是一个FILE

类型

指针

如果是打开文件,文件不存在的话

返回值

为空,如果存在就返回指向该文件的指针,如果是新建一个文件,返回值就是新建文件的指针,可以利用该指针实现对文件的读写功能。

至于判断是读还是写,是跟fopen第二个

参数

决定的,也就是由你自己决定。

代码举例:

FILE

*fp

fp=fopen("D:\\1.txt","r")

"r"代表是读如果D盘下确实有这个文件,fp就是指向该文件的一个指针,如果不存在,就是空。

fp=fopen("D:\\1.tx","w")

"w"表示写,返回值是指向新建文件的指针。

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

main()

{

FILE *fp

char *path="e:\\ge"

char *name

char *txt=".txt"

char *filepath

int i=0

name=(char*)malloc(3)

itoa(i,name,3)

filepath=(char *)malloc(strlen(path)+strlen(name)+strlen(txt)+1)

fp=(FILE *)malloc(100)

strcpy(filepath,path)

strcat(filepath,name)

strcat(filepath,txt)

printf("%s\n",filepath)

//*name=*name+1

//printf("%c\n",*name)

while(1)

{

fp=fopen(filepath,"r")

if(!fp)

{

fp=fopen(filepath,"w")

break

}

else

{

i++

itoa(i,name,3)

printf("%c",*name)

free(filepath)

filepath=NULL

filepath=(char *)malloc(strlen(path)+strlen(name)+strlen(txt)+1)

strcpy(filepath,path)

strcat(filepath,name)

strcat(filepath,txt)

printf("%s\n",filepath)

}

}

free(filepath)

}

写的可能比较繁琐

fp=fopen("d:\\test.txt",

"w")

fp=fopen("d:\\test.txt",

"rb")

"w"

写入模式

明显

要读取

写入

要用r模式

fread()函数

函数

用于读取二进制文件

文件要

"rb"模式打