9.文件操作

一.fgetc和fputc

示例代码

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

#pragma warning(disable:4996)


// 测试文件读写
void main()
{

    FILE *fp = NULL;
    char a[100] = "-------------------------";
    int i = 0;


    char *fname = "C:/1.txt";
    fp = fopen(fname,"a+");

    if (NULL == fp)
    {
        printf("文件打开失败\n");
    }

    while (!feof(fp))
    {
        char tmpc = fgetc(fp);
        printf("%c", tmpc);
    }


    for (i = 0; i < strlen(a); i++)
    {
        fputc(a[i],fp); // 将指定字符串写入到输出流中
    }

    if (fp != NULL)
    {
        fclose(fp);
    }

    system("pause");
}

二.fputs和fgets

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

#pragma warning(disable:4996)



void main()
{

    FILE *fp = NULL;
    char a[100] = "\n鶾专业化 夫";
    int i = 0;


    char *fname = "C:/1.txt";
    fp = fopen(fname,"a+");

    if (NULL == fp)
    {
        printf("文件打开失败\n");
        return;
    }

    
    char mystring[100];
    while (fgets(mystring, 100, fp) != NULL)
    {
        printf("%s",mystring);
    }
    

    // 写入一行
     fputs(a,fp);

    if (fp != NULL)
    {
        fclose(fp);
    }

    system("pause");
}

 

posted @ 2017-06-01 10:51  夜行过客  阅读(257)  评论(0编辑  收藏  举报