C语言处理文件

  C写入数据到文件

#include <stdio.h>
#include <string.h>

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

  写入一串数据:

#include <stdio.h>

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

  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
");
    }else{
        printf("open success
");
        fclose(p);
    }
    return 0;
}

  

  fscanf读取文件并打印:

#include <stdio.h>

int main() {

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

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

#include <stdio.h>

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

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

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

作者: NONO
出处:http://www.cnblogs.com/diligenceday/
企业网站:http://www.idrwl.com/
开源博客:http://www.github.com/sqqihao
QQ:287101329
微信:18101055830 

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

原文地址:https://www.cnblogs.com/diligenceday/p/7094987.html