C语言里如何把已有的字符串写入文件里?

Python014

C语言里如何把已有的字符串写入文件里?,第1张

设要写入的数字是int型,则用控制字符串%d和%s来完成,举例代码行如下:

fprintf(fp,"%d %s\n",12345,"abcdefg")

其中:fp是成功写打开文件指针。此代码行先向文件写入整型数字12345,再加一个空格,接着写入字符串abcdefg,然后写入'\n'。

#include "stdio.h"

#include "string.h"

void main()

{

char a[6]="china"

char temp[1024]

int n=0//记录有多少个china

FILE *outFile=fopen("c:\b.txt","r+")

FILE *inFile=fopen("c:\a.txt","r+")

while(fgets(temp,500,inFile)!=NULL)

{

int k=0

for(int i=0i<strlen(temp)i++)

{

if(temp[i]==a[k] &&k<strlen(a))

{

k++

}

else

{

if(k==strlen(a))

{

n++

fprintf(outFile,"%s

",a)

}

k=0

}

}

}

}

在C盘要有这两个文件。。。

a文件中可能有多个china ,指定加到第几行自己看情况 在设置一个int变量记录就行了

C语言fwrite写入文件可以参考以下的代码:

// 定义一个学生结构体

struct Student_type

{

char name[10]

int num

int age

char addr[30]

}stud[40]

int i

FILE *fp  // 定义一个文件指针fp

fp = fopen("stu.dat", "wb")  // 以二进制可写方式打开stu.dat文件

// 将40个学生的记录写入文件stu.dat中

for(i=0 i<40 i++)

fwrite(&stud[i], sizeof(struct Student_type), 1, fp)

扩展资料:

fwrite函数用法

size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream)

返回值:返回实际写入的数据块数目

1、buffer:是一个指针,对fwrite来说,是要获取数据的地址

2、size:要写入内容的单字节数

3、count:要进行写入size字节的数据项的个数

4、stream:目标文件指针

5、返回实际写入的数据项个数count

说明:写入到文件的哪里与文件的打开模式有关,如果是w+,则是从file pointer指向的地址开始写,替换掉之后的内容,文件的长度可以不变,stream的位置移动count个数;如果是a+,则从文件的末尾开始添加,文件长度加大。

fseek对此函数有作用,但是fwrite函数写到用户空间缓冲区,并未同步到文件中,所以修改后要将内存与文件同步可以用fflush(FILE *fp)函数同步。

参考资料来源:百度百科-fwrite

利用VC软件通过代码书写就可以将数据写入文件。

首先打开VC++6.0。

选择文件,新建。

选择C++ source file 新建一个空白文档。

先声明头文件#include <stdio.h>。

写上主函数

void main

主要代码

FILE *infile,*outfile,*otherfile

char input

char inputs[10]

int i=0

infile = fopen("d:\\infile.txt","r+")//用fopen函数打开文件

outfile = fopen("d:\\outfile.txt","a+")//用fopen函数打开文件

if ( !infile )

printf("open infile failed....\n")

if ( !outfile)

printf("open outfile failed...\n")

printf("*********************************************\n")

printf("** This program is to show file operation! **\n")

printf("** The input file is:                      **\n")

printf("**                       d:\\infile.txt     **\n")

printf("** The contents in this file is:           **\n")

printf("\n")

for()

{

input = fgetc(infile)//死循环读出文件内容

printf("%c",input)

putc(input,outfile)//写入内容

i++

if(input == '\n' || input == EOF)

break

}

fclose(infile)

fclose(outfile)

scanf("%d",i)

运行结果