加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

文件操作(写)

发布时间:2020-12-13 22:35:45 所属栏目:Linux 来源:网络整理
导读:/* **file.c** */ #include stdio.h int main(){ // 用写的方式打开一个文件 // w的意思是文件如果不存在,就建立一个文件,如果文件存在就覆盖 FILE *p = fopen( " /home/exbot/wangqinghe/C/20190716/file1.txt " , " w " ); fputs( " hello worldn " ,p)
/***
file.c
***/
#include<stdio.h>

int main()
{
    //用写的方式打开一个文件    
    //w的意思是文件如果不存在,就建立一个文件,如果文件存在就覆盖
    FILE *p = fopen("/home/exbot/wangqinghe/C/20190716/file1.txt","w");
    fputs("hello worldn",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] = n;
        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,stdin) != EOF)
    {
        printf("s = %sn",s);
        fputs(s,p);
    }
    fclose(p);
    return 0;
}

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

?

还可以使用scanf(“%[^n]”,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,sizeof(s));
        scanf("%[^n]","exit") == 0)
            break;
        printf("s = %sn",p);
    }
    fclose(p);
    return 0;
}

有问题,待解决。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读