文件IO 标准输入流,标准输出流,标准错误流

1:思维导图

2:使用3语言编写一个简易的界面,界面如下

1:标准输出流

2:标准错误流

3:文件流 要求:按1的时候,通过printf输出数据,按2的时候,通过perror输出数据,按3的时候将输入写入文件中 同时通过dup2函数,将标准错误流重定向到错误日志,将文件流重定向到终端

源代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fcntl.h>             
#include <unistd.h>
int main(int argc, const char *argv[])
{
	int a=0;
	while(1)
	{
		printf("请选择功能\n");
		scanf("%d",&a);
        while(getchar()!=10);
        int out=dup(1);//记录标准输出流
		int o=open("1.txt",O_RDWR|O_CREAT|O_TRUNC,0666);

        int err=open("error.txt",O_RDWR|O_CREAT|O_TRUNC,0666);//错误日志
		int e=dup(2);//标准错误流

		switch (a)
		{
			case 1:
				{
					printf("标准输出流\n");
					break;
				}
			case 2:
				{
					FILE* p=fopen("2.txt","r");
					if(NULL==p)
					{
						perror("标准错误流\n");
					}
					break;
				}
			case 3:
				{
					//从程序流向文件
					fprintf(stdout,"请输入要写入的数据\n");
					char a[20]={0};
					fscanf(stdin,"%s",a);
					dup2(o,1);//标准输出流重定向
					printf("数据输出\n");
					printf("%s\n",a);
					fflush(stdout);//刷新缓存

					//从程序流向终端
					dup2(out,1);//重定向,指向标准输出流
					printf("%s\n",a);
					close(o);//关闭						

					//错误流
					dup2(err,2);//标准错误流重定向
					FILE* p1=fopen("2.txt","r");
					if(NULL==p1)
					{
						perror("标准错误流\n");//展示错误日志
					}

					
					break;
				}
			case 4:
				{
					return 0;
				}
		}
	}
	return 0;
}

 运行截图:

 

3:使用stat函数判断一个文件是否存在 同组人可执行 权限,如果存在则去除该权限,如果不存在则追加该权限 自己想办法查询 更改文件权限的函数是什么

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <fcntl.h>             
#include <unistd.h>
int main(int argc, const char *argv[])
{
	struct stat a={0};
	stat(argv[1],&a);
	mode_t mode=a.st_mode;
	if((mode|00010)==mode)
	{
		printf("拥有可执行权限\n");
		int a=chmod(argv[1],0664);
		if(a==-1)
		{
			printf("修改失败\n");
		}else{
			printf("修改成功\n");
		}
	}
	else
	{
		printf("没有可执行权限\n");	
		int b=chmod(argv[1],0661);
		if(b==-1)
		{
			printf("修改失败\n");
		}
		else{
			printf("修改成功\n");
		}
	}
	return 0;
}

运行截图:

 修改前:

修改后: 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值