C语言如何实现对txt文件的读取和写入

Python010

C语言如何实现对txt文件的读取和写入,第1张

1、使用VS新建空工程,直接点击确定,如下所示。

2、新建c文件,用于C语言编译器,输入main.c文件,如下所示。

3、参考代码:

#include <stdio.h>

int main()

{

  //下面是写数据,将数字0~9写入到data.txt文件中

  FILE *fpWrite=fopen("data.txt","w")

  if(fpWrite==NULL)

  {

      return 0

  }

  for(int i=0i<10i++)

      fprintf(fpWrite,"%d ",i)

  fclose(fpWrite)

  //下面是读数据,将读到的数据存到数组a[10]中,并且打印到控制台上

  int a[10]={0}

  FILE *fpRead=fopen("data.txt","r")

  if(fpRead==NULL)

  {

      return 0

  }

  for(int i=0i<10i++)

  {

      fscanf(fpRead,"%d ",&a[i])

      printf("%d ",a[i])

  }

  getchar()//等待

  return 1

}

4、编译完成后,运行exe程序,执行后显示console程序。

如果预知前面的是英文后面的是中文,即可分开:

#include<stdio.h>

#define N 100

void main() { FILE *fpchar s[256],y[N][20],h[N][20]int i,n

if ( fp=fopen("c:\\data\\text.txt","r") ) {

  n=0

  while ( !feof(fp) ) {

    fgets(s,256,fp)sscanf("%s%s",y[n],h[n])n++if ( n>=N ) break

  }

  fclose(fp)

  printf("英文: ")for ( i=0i<ni++ ) printf("%s ",y[i])printf("\n")

  printf("中文: ")for ( i=0i<ni++ ) printf("%s ",h[i])printf("\n")

} else printf("无法打开文件读取。\n")

}

如果中英文顺序不一定,且不会有中英文混合单词:

#include<stdio.h>

#include<string.h>

#define N 100

void main() { FILE *fpchar s[256],y[N][20],h[N][20]int i,n

if ( fp=fopen("c:\\data\\text.txt","r") ) {

  n=0

  while ( !feof(fp) ) {

    fgets(s,256,fp)sscanf("%s%s",y[n],h[n])

    if ( y[n][0]<0 ) { strcpy(s,y[n])strcpy(y[n],h[n])strcpy(h[n],s)} //汉字字符ASCII码小于0

    n++if ( n>=N ) break

  }

  fclose(fp)

  printf("英文: ")for ( i=0i<ni++ ) printf("%s ",y[i])printf("\n")

  printf("中文: ")for ( i=0i<ni++ ) printf("%s ",h[i])printf("\n")

} else printf("无法打开文件读取。\n")

}

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

}