怎样用C语言写入\读取一个TXT文件

用for循环读取一个文件中的数据,在输出
for循环一个数组写入另一个文件

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

#include<stdio.h>

#define N 100

void main() { FILE *fp; char 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=0;i<n;i++ ) printf("%s ",y[i]); printf("\n");

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

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

}

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

#include<stdio.h>

#include<string.h>

#define N 100

void main() { FILE *fp; char 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=0;i<n;i++ ) printf("%s ",y[i]); printf("\n");

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

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

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-05-07
输入文件:shuru.txt ; 数据格式为:21 52 36 54 ...
输出文件:shuchu.txt ;

#include <stdlib.h>
#include <stdio.h>

void main()
{
FILE *in, *out;
int a[10],i;

if((in = fopen("shuru.txt","rb")) == NULL)
{
printf("can not open infile:\n");
exit(0);
}
if((out = fopen("shuchu.txt","w")) == NULL)
{
printf("can not open outfile:\n");
exit(0);
}

for(i = 0; i < 10; i++)
a[i] = getw(in);

for(i = 0; i < 10; i++)
putw(a[i],out);

fclose(in);
fclose(out);
}

注意: txt文件必须以二进制形式打开 即 “rb”
输出 “w” 或“wb”都行
第2个回答  推荐于2016-07-29
s_n(struct mem apeo[],int bn)
{
FILE *wfp;
int i;
wfp=fopen("m_info","wb+");
if(wfp!=NULL)
{
for(i=0;i<bn;i++)
{
if(fwrite(&apeo[i],sizeof(struct mem),1,wfp)!=1)
printf("\t\t\t\tfile write error\n");
}
}
else printf("fail to open file\n");
fclose(wfp);
}

上面是一个实例,主要是用fread();来读,用fwrite();来写。

格式为fread(buffer,size,count,fp) ;其中buffer是一个指针,它指向用来存储读出数据的地址。
size是每次读出数据的大小,count是连续读多少次;fp也是一个(文件)FILE类型的指针,它指被读取数据的文件。

fwrite(buffer,size,count,fp)大致一样就是buffer变成指向存储待写入数据的地址,fp指向存储地址;

另外使用两个函数之前还要用fp=fopen("save.txt","r+");这个函数来打开文件

"save.txt"为文件名,,"r+"为打开方式,r+为以可读可写的方式打开一个文件

"+"为以可读可写的方式创建一个文件;

另外还用很多类似的函数想知道的话就发信息过来;本回答被提问者采纳
相似回答