C 语言的文件,流, 键盘输入, 重定向

news2024/10/7 10:18:38

文章目录

  • The End of File
  • 重定向 redirection
    • 输入重定向
    • 输出重定向
    • 组合重定向

A file is an area of memory in which information is stored. Normally, a file is kept in some sort of permanent memory, such as a hard disk, USB flash drive, or optical disc, such as a DVD.

C has many library functions for opening, reading, writing, and closing files. On one level, it can deal with files by using the basic file tools of the host operating system. This is called low-level I/O . Because of the many differences among computer systems, it is impossible to create a standard library of universal low-level I/O functions, and ANSI C does not attempt to do so; however, C also deals with files on a second level called the
standard I/O package. This involves creating a standard model and a standard set of I/O functions for dealing with files. At this higher level, differences between systems are handled by specific C implementations so that you deal with a uniform interface.

Different systems, for example, store files differently. Some store the file contents in one place and information about the file elsewhere. Some build a description of the file into the file itself. In dealing with text, some systems use a single newline character to mark the end of a line. Others might use the combination of the carriage return and linefeed characters to represent the end of a line. Some systems measure file sizes to the nearest byte; some measure in blocks of bytes.

When you use the standard I/O package, you are shielded from these differences. Therefore, to check for a newline, you can use if (ch == '\n') . If the system actually uses the carriagereturn/ linefeed combination, the I/O functions automatically translate back and forth between the two representations.

Conceptually, the C program deals with a stream instead of directly with a file. A stream is an idealized flow of data to which the actual input or output is mapped. That means various kinds of input with differing properties are represented by streams with more uniform properties. The process of opening a file then becomes one of associating a stream with the file, and reading and writing take place via the stream.

C treats input and output devices the same as it treats regular files on storage devices. In particular, the
keyboard and the display device are treated as files opened automatically by every C program. Keyboard input is represented by a stream called stdin , and output to the screen (or teletype or other output device) is represented by a stream called stdout . The getchar() , putchar() , printf() , and scanf() functions are all members of the standard I/O package, and they deal with these two streams.

You can use the same techniques with keyboard input as you do with files. For example, a program reading a file needs a way to detect the end of the file so that it knows where to stop reading. Therefore, C input functions come equipped with a builtin, end-of-file detector. Because keyboard input is treated like a file, you should be able to use that end-of-file detector to terminate keyboard input, too. Let’s see how this is done, beginning with files.

The End of File

One method to detect the end of a file is to place a special character in the file to mark the end. This is the method once used, for example, in CP/M, IBM-DOS, and MS-DOS text files. Today, these operating systems may use an embedded Ctrl+Z character to mark the ends of files. At one time, this was the sole means these operating systems used, but there are other options now, such as keeping track of the file size. So a modern text file may or may not have an embedded Ctrl+Z, but if it does, the operating system will treat it as an end-of-file marker.

A second approach is for the operating system to store information on the size of the file. If a file has 3000 bytes and a program has read 3000 bytes, the program has reached the end. MS-DOS and its relatives use this approach for binary files because this method allows the files to hold all characters, including Ctrl+Z. Newer versions of DOS also use this approach for text files. Unix uses this approach for all files.

C handles this variety of methods by having the getchar() function return a special value when the end of a file is reached, regardless of how the operating system actually detects the end of file. The name given to this value is EOF (end of file). Therefore, the return value for getchar() when it detects an end of file is EOF . The scanf() function also returns EOF on detecting the end of a file. Typically, EOF is defined in the stdio.h file as follows:

#define EOF (-1)

getchar() returns a value in the range 0 through 127 , because those are values corresponding to the standard character set, but it might return values from 0 through 255 if the system recognizes an extended character set. In either case, the value -1 does not correspond to any character, so it can be used to signal the end of a file.

Some systems may define EOF to be a value other than -1 , but the definition is always different from a return value produced by a legitimate input character. If you include the stdio.h file and use the EOF symbol, you don’t have to worry about the numeric definition. The important point is that EOF represents a value that signals the end of a file was detected; it is not a symbol actually found in the file.

Okay, how can you use EOF in a program? Compare the return value of getchar() with EOF . If they are different, you have not yet reached the end of a file. In other words, you can use an expression like this:

while ((ch = getchar()) != EOF)

What if you are reading keyboard input and not a file? Most systems (but not all) have a way to simulate an end-of-file condition from the keyboard.

程序示例:

下面的程序从键盘读入内容, 再打印读入的内容.

#include<stdio.h>

int main(void)
{
	int ch;
	while ((ch = getchar()) != EOF)
	{
		putchar(ch);
	}

	return 0;
}

结果:

ok
ok
hello
hello
^Z

Ctrl + Z 模拟文件结尾, 结束键盘输入.

The concept of simulated EOF arose in a command-line environment using a text interface. In such an environment, the user interacts with a program through keystrokes, and the operating system generates the EOF signal. Some practices don’t translate particularly well to graphical interfaces, such as Windows and the Macintosh, with more complex user interfaces that incorporate mouse movement and button clicks. The program behavior on encountering a simulated EOF depends on the compiler and project type.

这里需要把 ch 声明为 int 类型, 因为 char 类型只能储存无符号整数, 但是这里需要返回 -1 以便和 EOF 进行比较, 且 getchar() 函数的返回值也是 int 类型的.

The fact that getchar() is type int is why some compilers warn of possible data loss if you assign the getchar() return value to a type char variable.

重定向 redirection

Input and output involve functions, data, and devices.

默认情况下, C 使用标准 I/O 包查找标准输入作为输入源, 就是 stdin 流, 输入设备是键盘, 输入数据流由字符组成.

程序不关心是从哪里获得数据, 这些设备用一个更抽象更统一的概念来表达, 即流. I/O 函数都是和流做交互而不是和某个硬件设备或某个文件.

因此程序可以从磁带 (magnetic tape), 穿孔卡 (punched cards) 或电传打字机 (teletype) 或者文件中获取输入.

程序可以通过两种方式使用文件, 一种是显式地使用某种函数打开文件, 关闭文件, 读取文件, 写入文件等等. 第二种方法是重定向程序从文件输入或输出到文件.

One major problem with redirection is that it is associated with the operating system, not C. However, the many C environments, including Unix, Linux, and the Windows Command - Prompt mode, feature redirection, and some C implementations simulate it on systems lacking the feature.

程序:

#include<stdio.h>

int main(void)
{
	int ch;
	while ((ch = getchar()) != EOF)
	{
		putchar(ch);
	}

	return 0;
}

程序名称: echo_eof.c

编译程序得到可执行文件: echo_eof.exe

如图:

在这里插入图片描述

在命令行模式下输入 echo_eof 即可执行这个程序, 如图:

在这里插入图片描述

输入重定向

现在假设将程序的输入重定向到文件 word 中, 先建立文本文件 word, 内容为: hello world!

如图:

在这里插入图片描述

注意, words 文件没有后缀.

在命令行中重定向输入为文件 words:

在这里插入图片描述

The < symbol is a Unix and Linux and DOS/Windows redirection operator. It causes the words file to be associated with the stdin stream, channeling the file contents into the echo_eof program. The echo_eof program itself doesn’t know (or care) that the input is coming from a file instead of the keyboard. All it knows is that a stream of characters is being fed to it, so it reads them and prints them one character at a time until the end of file shows up. Because C puts files and I/O devices on the same footing, the file is now the I/O device.

With Unix, Linux, and Windows Command Prompt, the spaces on either side of the < are optional.

输出重定向

还可以把 echo_eof 的输出重定向到文件, 使得该程序从键盘读取输入, 再将其保存在文件中, 如图:

在这里插入图片描述

只有在一行的开头输入 Ctrl + Z 才能结束输入.

The > is a second redirection operator. It causes a new file called mywords to be created for your use, and then it redirects the output of echo_eof (that is, a copy of the characters you type) to that file. The redirection reassigns stdout from the display device (your screen) to the mywords file instead. If you already have a file with the name mywords , normally it would be erased and then replaced by the new one. (Many operating systems, however, give you the option of protecting existing files by making them read-only.) All that appears on your screen are the letters as you type them, and the copies go to the file instead. To end the program, press Ctrl+D (Unix) or Ctrl+Z (DOS) at the beginning of a line.

在这里插入图片描述

组合重定向

Now suppose you want to make a copy of the file mywords and call it savewords . Just issue this next command:

echo_eof < mywords > savewords

and the deed is done. The following command would have worked as well, because the order of redirection operations doesn’t matter:

echo_eof > savewords < mywords

Beware: Don’t use the same file for both input and output to the same command.

echo_eof < mywords > mywords  // wrong

The reason is that > mywords causes the original mywords to be truncated to zero length before it is ever used as input.

In brief, here are the rules governing the use of the two redirection operators ( < and > ) with Unix, Linux, or Windows/DOS:

■ A redirection operator connects an executable program (including standard operating system commands) with a data file. It cannot be used to connect one data file to another, nor can it be used to connect one program to another program.

■ Input cannot be taken from more than one file, nor can output be directed to more than one file by using these operators.

■ Normally, spaces between the names and operators are optional, except occasionally when some characters with special meaning to the Unix shell or Linux shell or the Windows Command Prompt mode are used.

Unix, Linux, and Windows/DOS also feature the >> operator, which enables you to add data to the end of an existing file, and the pipe operator ( | ), which enables you to connect the output of one program to the input of a second program.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/859499.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

基于关系有向图的知识推理2022ACM 8.9+8.10

基于关系有向图的知识推理 摘要介绍相关工作基于路径的方法基于GNN的方法 关系有向图RED-GCNr-digraph递归编码学习用于查询的基本信息 实验 摘要 知识图推理旨在从已有的知识中推断出新的事实。基于关系路径的方法在文献中显示出较强的可解释性和归纳推理能力。然而&#xff…

如何进行游戏平台搭建?

游戏平台搭建涉及多个步骤和技术&#xff0c;下面是一个大致的指南&#xff1a; 市场调研和定位&#xff1a;首先&#xff0c;要了解游戏市场和受众的需求&#xff0c;选择适合的游戏类型和定位。 选择平台类型&#xff1a;决定是要搭建网页平台、移动应用平台还是其他类型的…

Vue3 —— to 全家桶及源码学习

该文章是在学习 小满vue3 课程的随堂记录示例均采用 <script setup>&#xff0c;且包含 typescript 的基础用法 前言 本篇主要学习几个 api 及相关源码&#xff1a; toReftoRefstoRaw 一、toRef toRef(reactiveObj, key) 接收两个参数&#xff0c;第一个是 响应式对象…

专治疗懒病:GO、KEGG富集分析一体函数

之前我们写过GO、KEGG的富集分析&#xff0c;参见&#xff1a;补充更新&#xff1a;GO、KEGG&#xff08;批量分组&#xff09;分析及可视化。演示了差异基因KEGG或者GO的分析流程。其实差异基因的富集分析输入的文件只需要一组基因就可以了。所以我们发挥了专治懒病的优良传统…

【MySQL】创建高级联结

目录 一、使用表别名 二、使用不同类型的联结 1.自联结 2.自然联结 3.外部联结 3.使用带聚集函数的联结 4.使用联结和联结条件 一、使用表别名 别名除了用于列名和计算字段外&#xff0c;SQL还允许给表名起别名。 起别名有两个好处&#xff1a; 一个是缩短SQL语句&am…

群晖6.X便捷的安装cpolar内网穿透

群晖6.X便捷的安装cpolar内网穿透 文章目录 群晖6.X便捷的安装cpolar内网穿透前言1. 下载cpolar的群晖套件1.1 打开群晖套件中心1.2 选择“手动安装”1.3 选择下载cpolar套件位置 2. 打开cpolar的Web-UI界面3. 注册会员 前言 随着硬件设备和软件技术的发展&#xff0c;以及数据…

ElasticsSearch基础概念和安装

ElasticSearch基础概念以及可视化界面安装 文章目录 ElasticSearch基础概念以及可视化界面安装1、引言2、基本概念3、倒排索引机制3.1、倒排索引 4、使用docker安装ElasticSearch4.1、下载镜像文件4.2 、创建实例,启动es 5.安装Kibana 1、引言 Elastic 的底层是开源库 Lucene。…

朋友圈点赞截图生成,制作朋友圈网页​

支持纯文字内容&#xff0c;图文内容&#xff0c;单图&#xff0c;多图。自定义点赞数量、自定义评论&#xff0c;随机头像和自定义头像。 这个工具基本支持我们所需要的所有功能。可以说是目前最全的朋友圈页面生成器。 朋友圈页面样式是Iphone pro 14上的效果&#xff0c;几…

OneFlow 中的 Softmax

Softmax 是深度学习模型中的常见算子。PyTorch 的 Softmax 算子直接调用 cuDNN 的接口。而 OneFlow 内部针对输入数据的类别数量&#xff0c;采用3个 kernel 来分别处理&#xff0c;在多数情况下都可以获得比 cuDNN 更优的性能表现。下面对其实现进行介绍。OneFlow 的静态分层结…

Leetcode24 两两交换链表相邻的节点

迭代解法&#xff1a; class Solution {public ListNode swapPairs(ListNode head) {ListNode dummyHead new ListNode(0);dummyHead.next head;ListNode temp dummyHead;while (temp.next ! null && temp.next.next ! null) {ListNode node1 temp.next;ListNode n…

谷粒商城第十一天-品牌管理中关联分类

目录 一、总述 二、前端部分 1. 调整查询调用 2. 关联分类 三、后端部分 四、总结 一、总述 之前是在商品的分类管理中直接使用的若依的逆向代码 有下面的几个问题&#xff1a; 1. 表格上面的参数填写之后&#xff0c;都是按照完全匹配进行搜索&#xff0c;没有模糊匹配…

化工行业案例 | 甄知科技助力万华化学重构IT服务价值,打造信息中心ERP!

随着科技的发展&#xff0c;新材料的应用领域与日俱增&#xff0c;近年来&#xff0c;全球化工新材料产业发展整体步入高技术引领、产品迭代速度快、产业规模和需求不断扩大的阶段。一体化协同与数字化转型策略是实现化工新材料生产原料自给、节能降耗、降低排放和物料成本的重…

验证码识别全流程实战

验证码的历史与发展 验证码&#xff0c;全称为 “Completely Automated Public Turing test to tell Computers and Humans Apart”&#xff0c;即全自动区分计算机和人类的图灵测试&#xff0c;Captcha。早在上个世纪 90 年代&#xff0c;为了防止恶意的网络机器人行为&#x…

matplotlib 笔记:hist2d 2D直方图

创建二维直方图&#xff0c;用于显示数据分布的图表将数据划分成不同的区间&#xff08;bin&#xff09;&#xff0c;并统计每个区间内数据点的数量 1 基本画法 默认bin的数量是10*10 N 1000 x np.random.randn(N) y np.random.randn(N) plt.hist2d(x, y) 2 修改bin的…

英特尔处理器被曝出“Downfall”漏洞:可窃取加密密钥

今日&#xff0c;谷歌的一位高级研究科学家利用一个漏洞设计了一种新的CPU攻击方法&#xff0c;该漏洞可影响多个英特尔微处理器系列&#xff0c;并允许窃取密码、加密密钥以及共享同一台计算机的用户的电子邮件、消息或银行信息等私人数据。 该漏洞被追踪为CVE-2022-40982&am…

nginx配置gzip

在 Nginx 中启用 Gzip 压缩可以大幅减少传输内容的大小&#xff0c;从而加快网页加载速度。 打开 Nginx 的配置文件&#xff0c;通常是 /etc/nginx/nginx.conf 或者 /etc/nginx/conf.d/default.conf。找到 http 配置块&#xff0c;在其中添加以下代码来开启 Gzip 压缩&#xff…

pikachu中RCE出现乱码的解决的方案

exec “ping” 输入127.0.0.1 这种乱码的解决办法就是在pikachu/vul/rce/rce_ping.php目录里面的第18行代码 header("Content-type:text/html; charsetgbk");的注释打开即可。 BUT但是吧&#xff01;又出现了其他的乱码&#xff01;但是搞完这个再把它给注释掉就行了…

pyscenic分析:视频教程

我们之前更新过pyscenic的教程&#xff1a;pySCENIC单细胞转录因子分析更新&#xff1a;数据库、软件更新。我们也说过&#xff0c;我们号是放弃R语言版的SCENIC的分析了&#xff0c;因为它比较耗费计算资源和时间&#xff0c;所以我们的单细胞转录因子分析教程都是基于pysceni…

轻松预约,尽享美食,详解餐厅预约小程序的设计与实现

随着智能手机的普及和人们生活水平的提高&#xff0c;餐厅预约已经成为人们日常生活中的一部分。为了更好地满足人们的需求&#xff0c;许多餐厅开始使用小程序来提供更方便快捷的预约服务。本文将介绍如何制作一款餐厅预约小程序的详细步骤。 1. 进入乔拓云网后台&#xff0c;…

JVM:对象的内存布局

对象的内存布局 对象在堆内存中的存储布局可以划分为三个部分&#xff1a;对象头&#xff08;Header&#xff09;、实例数据&#xff08;Instance Data&#xff09;和对齐填充&#xff08;Padding&#xff09;。 ps&#xff1a;这个对象所属类的方法信息&#xff0c;静态变量…