c语言文件读写 实例

发布网友

我来回答

4个回答

热心网友

  C语言标准库提供了一系列文件I/O函数用于文件操作,比如fopen()用于打开文件、fread()、fwrite()用于读写文件、fseek()用于设置操作位置等等,一般C语言教程上都有文件I/O一章,细致内容,可以找本教科书学习一下。 下面的示例,是向名为1.txt的文件附加hello world字符串。


#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp = fopen("1.txt", "a+");
if (fp==0) { printf("can't open file\n"); return 0;}
fseek(fp, 0, SEEK_END);
char sz_add[] = "hello world\n";
fwrite(sz_add, strlen(sz_add), 1, fp);
fclose(fp);
return 0;
}

热心网友

用freopen

如下:
#include<stdio.h>
int s[100];
int main()
{
freopen("a.txt","r",stdin);

freopen("b.txt","w",stdout); //建议使用 .in文件 和 .out文件,在编译器里就能打开(如data.in , data.out)
/*其中,这两种格式是固定的
输入就是:freopen("文件名",“r”/*r代表read,只读*/,stdin/*必须这么写*/)

输出:freopen("文件名",“w”/*w代表write,写入*/,stdout/*必须这么写*/)
之后就按正常程序写就可以了
*/

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

{
scanf("%d",&s[i]);

}
/*顺序自行解决*/
for( i = 0 ; i < 10 ; i++)

{
printf("%d",s[i]);

}
/*这两步自动读入和输出到文件中*/

return 0;

}

热心网友

#define size 1000;

#include <stdio.h>
int main(){
int fd1= open("a",O_RDONLY,0);

int fd2 = open("b",O_RDWR|O_CREAT,00777);

cha buf1[size];

int n = read(fd1,buf1,size);

int i,num;
for(i = 0;i < size;i ++){
if(buf1[i] == '\0'){
break;
}
}
char tmp;
for(j = 0;j <= (i - 1)/2;j ++){
tmp = buf1[j];
buf1[j] = buf1[i - 1 -j];

buf1[i - 1 - j] = tmp;

}

write(fd2,buf,n);

}

热心网友

#include "stdio.h"
#include "stdlib.h"
int main(void){
FILE *p;
int b[10],i;
p = fopen("E:\\Csource\\read\\Debug\\a.txt","r");
if( p == NULL){
fprintf(stderr,"Error on open file a.txt\n");
exit(EXIT_FAILURE);
}
for(i=0; i<10; fscanf(p," %d",&b[i++]));
fclose(p);

p = fopen("E:\\Csource\\read\\Debug\\b.txt","w");
if( p == NULL){
fprintf(stderr,"Error on open file b.txt\n");
exit(EXIT_FAILURE);
}
for(i=9; i>=0; fprintf(p,"%d ",b[i--]));
fclose(p);
return 0;
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com