文件操作(写)

/***
file.c
***/
#include<stdio.h>

int main()
{
    //用写的方式打开一个文件    
    //w的意思是文件如果不存在,就建立一个文件,如果文件存在就覆盖
    FILE *p = fopen("/home/exbot/wangqinghe/C/20190716/file1.txt","w");
    fputs("hello world
",p);    //向文件中写入一个字符串
    fclose(p);    //关闭这个文件
    return 0;
}
/***
file1.txt
***/
#include<stdio.h>
#include<string.h>
int main()
{
    char s[1024] = {0};
    FILE *p = fopen("/home/exbot/wangqinghe/C/20190716/file1.txt","w");
    
    while(1)
    {
        memset(s,0,sizeof(s));
        scanf("%s",s);
        if(strcmp(s,"exit") == 0)
        {
            break;
        }
        int len = strlen(s);
        s[len] = '
';
        fputs(s,p);
    }
    fclose(p);
    return 0;
}

缺陷:scanf输入会将空格自动隔开下一行。

gcc已经禁止使用gets函数了。

接受带空格的字符出的方法,vs中可以使用gets_s函数,

linux环境下只能使用char *fgets(char *buf, int bufsize, FILE *stream);

fget(str,maxn,stdin); stdin表示接受从键盘中输入。

但是fgets输入是在缓冲区中读入的,不能接受在输入的时候判断输入的字符串来中断循环。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int maxn  = 1024;
int main()
{
    char s[1024] = {0};
    FILE *p = fopen("/home/exbot/wangqinghe/C/20190716/file1.txt","w");
    
    while(fgets(s,maxn,stdin) != EOF)
    {
        printf("s = %s
",s);
        fputs(s,p);
    }
    fclose(p);
    return 0;
}

可以输入到字符串中并打印出来,但是手动结束ctrl+v结束的话不能输出到文件中。

还可以使用scanf(“%[^ ]”,str);来实现这个功能

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int maxn  = 10;
int main()
{
    char s[1024] = {0};
    FILE *p = fopen("/home/exbot/wangqinghe/C/20190716/file1.txt","w");
    
    while(1)
    {
        //memset(s,0,sizeof(s));
        scanf("%[^
]",s);
        if(strcmp(s,"exit") == 0)
            break;
        printf("s = %s
",s);
        fputs(s,p);
    }
    fclose(p);
    return 0;
}

有问题,待解决。

原文地址:https://www.cnblogs.com/wanghao-boke/p/11196741.html