C语言创建TXT文档并写入内容

C语言创建TXT文档并写入内容,第1张

下面所有file模式,如果文件不存在,就创建文件。模式你自己选。另外还有很多其他函数,你自己看书。下面是最基本得的

file

*pfile

=

fopen("d:\\001.txt",

"rb")//以二进制方式打开d盘得001.txt文件

fseek(pfile,0l,seek_end)//将文件指针移动到文件末尾

unsigned

long

buflen

=

ftell(pfile)//获取文件长度

unsigned

char

*buf

=

new

unsigned

char[buflen]//创建改文件长度大小的一块内存用来放要读进来的文件内容

rewind(pfile)//指针移动到文件头

fread(buf,1,buflen,pfile)//将文件的内容全部读入buf中

fclose(pfile)//关闭文件

上面为读文件,下面为写文件

file

*pfile

2=

fopen("d:\\002.txt",

"wb")//以写二进制方式打开002.txt文件

fwrite(buf,1,buflen,pfile2)//将buf写入002.txt

fclose(pfile2);//关闭文件

int main(){

//以读的方式打开文件

FILE * fp1 = fopen("1.txt","r")

if(fp1 == NULL)

{

perror("fopen1 error")

exit(-1)

}

//以读的方式打开文件

FILE * fp2 = fopen("2.txt","r")

if(fp2 == NULL)

{

perror("fopen2 error")

exit(-1)

}

//以写的方式打开文件

FILE * fp3 = fopen("3.txt","w")

if(fp3 == NULL)

{

perror("fopen3 error")

exit(-1)

}

//初始化3个字符

char ch1 = '0'

while((ch1 = getc(fp1)) != EOF)

{

putc(ch1,fp3)

}

while((ch1 = getc(fp2)) != EOF)

{

putc(ch1,fp3)

}

//关闭文件1,2,3

fclose(fp1)

fclose(fp2)

fclose(fp3)

return 0

}

#include <stdio.h>

FILE * fp

void main()

{

fp=fopen("tmp.cpp","a")//a,在文件末尾追加内容

fprintf(fp,"888\n")//输出

//……………… 这里你可以输入一些你需要的代码。输入任意长度的话,你就在这里加上你需要输入的代码就行了

fclose(fp)

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11483028.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-16
下一篇2023-05-16

发表评论

登录后才能评论

评论列表(0条)

    1.txt","rb")以二进制方", "pubDate":"2023-05-16", "upDate":"2023-05-16" }
    保存
    1.txt","rb")以二进制方', author : '中国电信宽带测速', cat_name : 'IT百科', time_y_m : '2023年05月', time_d : '16', site_motto : '内存溢出' }; {script}{script}