C语言处理文件

  C写入数据到文件

#include <stdio.h>
#include <string.h> int main( ) {
FILE* fd = fopen("txt.txt","w+");
char a[] = "abcdefg";
for(int i=; i<strlen(a); i++ ){
fputc(a[i],fd);
};
fclose(fd);
return ;
}

  写入一串数据:

#include <stdio.h>

int main() {
FILE *f = fopen("txt.txt", "a+");
char str[] = "";
fprintf(f, "%s\n", str);
printf("%s", str);
fclose(f);
return ;
}

  mode有下列几种形态字符串:

  r 打开只读文件,该文件必须存在。
  r+ 打开可读写的文件,该文件必须存在。
  w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
  w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
  a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。
  a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。

  上述的形态字符串都可以再加一个b字符,如rb、w+b或ab+等组合,加入b 字符用来告诉函数库打开的文件为二进制文件,而非纯文字文件

  通过fopen创建并打开文件:

#include <stdio.h>

int main() {
FILE *p;
p = fopen("txt.txt", "r+");
if( p == NULL ) {
printf("open failed\n");
}else{
printf("open success\n");
fclose(p);
}
return ;
}

  

  fscanf读取文件并打印:

#include <stdio.h>

int main() {

    FILE *f = fopen("txt.txt", "r+");
char strs[];
fscanf(f, "%s", strs);
printf("stirng is %s\n", strs);
return ;
}

  使用fgetc获取一个字符并打印, 循环即可读取所有字符:

#include <stdio.h>

int main() {
FILE *p;
p = fopen("txt.txt", "r+");
int c;
while( (c=fgetc(p))!=EOF ) {
printf("%c",c);
}
return ;
}

  使用fwrite和fread也可以实现同样的效果:

#include <stdio.h>
void main( void )
{
FILE *stream;
char list[];
int i, numread, numwritten;
// 以文本方式打开文件
if( (stream = fopen( "fread.out", "w+t" )) != NULL ) // 如果读取无误
{
for ( i = ; i < ; i++ )
list[i] = (char)('z' - i);
numwritten = fwrite( list, sizeof( char ), , stream );
printf( "Wrote %d items\n", numwritten );
fclose( stream );
}
else
{
printf( "Problem opening the file\n" );
}
if( (stream = fopen( "fread.out", "r+t" )) != NULL ) // 文件读取
{
numread = fread( list, sizeof( char ), , stream );
printf( "Number of items read = %d\n", numread );
printf( "Contents of buffer = %.25s\n", list );
fclose( stream );
}
else
{
printf( "File could not be opened\n" );
}
}

C语言处理文件 作者: NONO
出处:http://www.cnblogs.com/diligenceday/

企业网站:http://www.idrwl.com/
开源博客:http://www.github.com/sqqihao
QQ:287101329

微信:18101055830

厦门点燃未来网络科技有限公司, 是厦门最好的微信应用, 小程序, 微信网站, 公众号开发公司

上一篇:ARIMA模型--粒子群优化算法(PSO)和遗传算法(GA)


下一篇:数值计算:粒子群优化算法(PSO)