29.12.2014 Views

C 语言程序设计(I)实验手册 - 中山大学软件学院

C 语言程序设计(I)实验手册 - 中山大学软件学院

C 语言程序设计(I)实验手册 - 中山大学软件学院

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

C 语 言 程 序 设 计 (I) 实 验 手 册<br />

中 山 大 学 软 件 学 院<br />

2011 年 9 月


教 学 目 的 与 教 学 要 求 :<br />

本 实 验 手 册 是 针 对 软 件 学 院 基 础 课 程 《 程 序 设 计 (I)》 的 上 机 训 练 而 编 写 的 。 教 学 的 主 要 任 务 是 从 应 用 和<br />

实 践 的 角 度 出 发 , 通 过 实 验 学 习 C 语 言 的 特 点 和 方 法 , 理 解 C 语 言 程 序 的 执 行 过 程 ; 学 会 独 立 编 写 和 调 试<br />

C 程 序 ; 掌 握 高 级 语 言 的 程 序 设 计 思 想 和 程 序 设 计 技 术 ; 建 立 良 好 的 编 程 风 格 , 提 高 分 析 问 题 和 解 决 问 题<br />

的 能 力 , 为 后 续 课 程 的 学 习 和 应 用 开 发 打 下 扎 实 的 理 论 和 实 践 基 础 。<br />

实 验 内 容<br />

实 验 周 次<br />

试 验 内 容<br />

1 C 程 序 的 设 计 环 境 和 运 行 方 法<br />

2 数 据 类 型 与 输 入 输 出 练 习 (I)<br />

3 数 据 类 型 与 输 入 输 出 练 习 (II)<br />

4 if, if/else 选 择 结 构 练 习<br />

5 熟 悉 sicily 平 台<br />

6 switch 选 择 结 构 练 习<br />

7 循 环 结 构 程 序 设 计 (I)<br />

8 循 环 结 构 程 序 设 计 (II)<br />

9 函 数 与 模 块 化 程 序 设 计 (I)<br />

10 函 数 与 模 块 化 程 序 设 计 (II)<br />

11 数 组 程 序 设 计 (I)<br />

12 数 组 程 序 设 计 (II)<br />

13 指 针 程 序 设 计 (I)<br />

14 指 针 程 序 设 计 (II)<br />

15 结 构 与 链 表<br />

16 文 件 操 作<br />

综 合 实 验 一<br />

综 合 实 验 二<br />

学 生 成 绩 管 理<br />

21 点 扑 克 牌 游 戏<br />

综 合 实 验 1、2 选 作 。<br />

所 有 实 验 必 须 独 立 完 成 , 成 绩 纳 入 期 末 总 评 , 不 得 抄 袭 !<br />

抄 袭 者 一 经 发 现 , 按 《 中 山 大 学 授 予 学 士 学 位 工 作 细 则 》 第 六 条 规 定 处 理 , 将 不 授 予 学 士 学 位 !<br />

- 1 -


目 录<br />

实 验 1 C 程 序 的 设 计 环 境 和 运 行 方 法 .................................................................................................................... 3<br />

实 验 2 数 据 类 型 与 输 入 输 出 练 习 (I).................................................................................................................... 4<br />

实 验 3 数 据 类 型 与 输 入 输 出 练 习 (II).............................................................................................................. 5<br />

实 验 4 if, if/else 选 择 结 构 练 习 ............................................................................................................................... 7<br />

实 验 5 熟 悉 sicily 平 台 .............................................................................................................................................. 8<br />

实 验 6 switch 选 择 结 构 练 习 ................................................................................................................................... 9<br />

实 验 7 循 环 结 构 程 序 设 计 (I) .......................................................................................................................... 10<br />

实 验 8 循 环 结 构 程 序 设 计 (II) ......................................................................................................................... 11<br />

实 验 9 函 数 与 模 块 化 程 序 设 计 (I)................................................................................................................... 12<br />

实 验 10 函 数 与 模 块 化 程 序 设 计 (II) ................................................................................................................. 13<br />

实 验 11 数 组 程 序 设 计 (I) .................................................................................................................................. 14<br />

实 验 12 数 组 程 序 设 计 (II) ................................................................................................................................. 15<br />

实 验 13 指 针 程 序 设 计 (I) .................................................................................................................................. 16<br />

实 验 14 指 针 程 序 设 计 (II) ................................................................................................................................. 17<br />

实 验 15 结 构 与 链 表 ............................................................................................................................................... 18<br />

实 验 16 文 件 操 作 ................................................................................................................................................... 19<br />

综 合 实 验 一 学 生 成 绩 管 理 .................................................................................................................................... 20<br />

综 合 实 验 二 21 点 扑 克 牌 游 戏 ............................................................................................................................... 21<br />

附 录 一 DEV-C++ 使 用 简 介 ...................................................................................................................................... 22<br />

附 录 二 程 序 模 板 示 例 ............................................................................................................................................ 28<br />

附 录 三 C 标 准 库 函 数 ( 摘 自 K&R,The C Programming Language) ............................................................................ 29<br />

- 2 -


实 验 1 C 程 序 的 设 计 环 境 和 运 行 方 法<br />

1. 熟 悉 Dev-C++( 参 照 附 录 一 ) 或 其 他 C 编 译 器 ( 如 VC 系 列 ,Borland C,Turbo C 等 ) 的 菜 单 组 成 及 功<br />

能 , 掌 握 如 何 利 用 该 编 译 器 进 行 C 程 序 的 编 辑 、 编 译 、 链 接 、 运 行 及 结 果 查 看 的 方 法 。<br />

2. 在 编 译 器 输 入 并 运 行 下 面 的 C 程 序 , 将 “***” 换 成 你 的 相 关 信 息 , 编 译 运 行 并 查 看 结 果 。<br />

#include <br />

int main()<br />

{<br />

printf("Hello C World!\nMy name is ***.\n\n"); /* 输 出 姓 名 */<br />

printf("My matric number is ***.\n"); /* 输 出 学 号 */<br />

}<br />

system("PAUSE"); /* 此 行 程 序 功 能 是 使 系 统 暂 停 , 显 示 结 果 , 按 任 意 键 继 续 */<br />

/* 在 Dev-C++ 中 需 要 , 其 他 编 译 器 , 如 VC 中 , 不 需 要 写 */<br />

return 0;<br />

3. 输 入 并 运 行 下 面 一 个 需 要 在 运 行 时 输 入 数 据 的 程 序 , 程 序 要 求 从 键 盘 输 入 三 个 浮 点 数 , 输 出 它 们 的 和 。<br />

#include <br />

Int mian()<br />

{<br />

float a, b, c, sum;<br />

printf(" input a,b,c: ")<br />

scanf("%f %f %f", &a, &b, &c);<br />

sum = a + b + c;<br />

printf("\nsum = %f\n", sum);<br />

}<br />

system("PAUSE");<br />

return 0;<br />

输 入 该 程 序 , 然 后 进 行 编 译 和 链 接 , 如 果 出 错 , 根 据 出 错 信 息 检 查 并 修 改 错 误 , 再 进 行 编 译 连 接 直 到<br />

没 有 错 误 为 止 。<br />

运 行 编 译 正 确 的 程 序 , 按 照 屏 幕 提 示 输 入 a、b、c 三 个 变 量 的 值 , 变 量 值 之 间 用 空 格 分 隔 , 输 入 完 毕<br />

按 回 车 键 【Enter】。 查 看 运 行 结 果 , 判 断 结 果 正 确 与 否 。<br />

- 3 -


实 验 2 数 据 类 型 与 输 入 输 出 练 习 (I)<br />

1. 编 程 计 算 下 面 数 学 表 达 式 的 值 , 其 中 的 a, b, c, x, y 作 为 变 量 。( 即 表 达 式 如 包 括 a, b, c, x 或 y, 从 键 盘<br />

输 如 相 应 的 数 值 , 程 序 输 出 表 达 式 计 算 结 果 。)<br />

(1)<br />

1200<br />

24 − 4 × 5<br />

(2)c×<br />

a<br />

b<br />

2 2<br />

+ , 实 验 报 告 中 贴 图 显 示 a=1, b=2, c=3 时 程 序 的 运 行 结 果 , 结 果 保 留 3 位 小 数 。<br />

(3)lnln(10 3.5 +2)<br />

(4)y+a%5*(int)(x+y)/2%4, 实 验 报 告 中 贴 图 显 示 a=7, x=8, y=9 时 程 序 的 运 行 结 果 。<br />

2. 编 写 一 个 C 程 序 , 使 用 输 入 函 数 scanf, 从 键 盘 按 顺 序 输 入 下 列 数 据 , 再 用 printf 将 输 入 数 据 原 样 打 印<br />

在 屏 幕 上 ( 数 据 间 用 空 格 隔 开 )。 注 意 数 据 的 类 型 和 scanf/printf 函 数 的 格 式 指 定 方 法 。<br />

输 入 :a 100 450.34 2147483648 4294967296 126.3455568<br />

输 出 :a 100 450.34 2147483648 4294967296 126.3455568<br />

3. 设 半 径 r = 2.5, 高 h = 4.5, 编 程 计 算 相 对 应 的 圆 面 积 、 圆 周 长 、 球 体 积 、 球 表 面 积 、 圆 柱 体 的 表 面 积 和<br />

体 积 。 显 示 保 留 两 位 小 数 的 结 果 。<br />

注 :printf/scanf 的 使 用 可 参 考 课 本 第 9 章 。<br />

- 4 -


实 验 3 数 据 类 型 与 输 入 输 出 练 习 (II)<br />

1. 输 入 并 运 行 下 面 程 序 , 对 照 程 序 分 析 运 行 结 果 , 并 分 析 原 因 :<br />

(1) 将 一 个 大 于 32767 的 长 整 型 数 赋 给 短 整 型 变 量 , 会 得 到 什 么 结 果 <br />

(2) 将 一 个 负 整 数 赋 给 一 个 无 符 号 的 变 量 , 会 得 到 什 么 结 果 <br />

(3) 将 一 个 字 符 型 赋 给 一 个 整 型 变 量 , 会 得 到 什 么 结 果 <br />

测 试 程 序 如 下 :<br />

#include <br />

int main()<br />

{<br />

short a;<br />

unsigned b;<br />

int c;<br />

a = 32768;<br />

printf("%d\n", a); /* 越 界 赋 值 */<br />

b = -100;<br />

printf("%u\n", b); /* 以 无 符 号 形 式 打 印 一 个 负 数 */<br />

c = 'c';<br />

printf("%d\n", c); /* 以 整 数 类 型 打 印 一 个 字 符 */<br />

}<br />

system("PAUSE");<br />

return 0;<br />

2. 编 程 求 4 个 输 入 数 据 的 平 均 值 :(1)4 个 整 数 ,(2)4 个 任 意 数 字 ( 可 能 整 数 , 可 能 浮 点 数 )。<br />

要 求 输 入 前 有 提 示 “please input the four integers: ” 或 者 “please input four numbers: ”。<br />

计 算 相 应 的 平 均 值 并 输 出 :“Average **, **, ** and **, you will get **.”<br />

输 入 样 例 1:please input the four integers : 1 2 3 4 ( 整 数 )<br />

输 出 样 例 1:Average 1, 2, 3 and 4, you will get 2.<br />

输 入 样 例 2:please input the four numbers : 1 2 3 4.4 ( 任 意 数 )<br />

输 出 样 例 2:Average 1, 2, 3 and 4.4, you will get 2.6.<br />

- 5 -


3. 输 入 并 运 行 下 面 的 程 序 :<br />

#include <br />

int main()<br />

{<br />

int a, b, c;<br />

a = getchar();<br />

b = getchar();<br />

c = getchar();<br />

printf("a=%d b=%d c=%d\n",a,b,c);<br />

printf("a=%c b=%c c=%c\n",a,b,c);<br />

}<br />

system("PAUSE");<br />

return 0;<br />

输 入 : 1【Enter】<br />

ab【Enter】<br />

试 解 释 本 题 程 序 的 输 出 结 果 。<br />

如 果 希 望 用 scanf 函 数 替 代 getchar 函 数 达 到 一 样 的 效 果 , 应 该 怎 么 做 请 写 出 修 改 程 序 。<br />

- 6 -


实 验 4<br />

if, if/else 选 择 结 构 练 习<br />

1. 编 程 求 解 分 段 函 数 的 值 :<br />

f(x) =<br />

2x+5 (x


实 验 5<br />

熟 悉 sicily 平 台<br />

【 期 末 上 机 考 试 】<br />

为 加 强 软 件 工 程 专 业 各 方 向 本 科 生 的 实 践 能 力 培 养 , 顺 应 IT 行 业 对 工 程 人 才 的 需 求 , 中 山 大 学 软 件 学<br />

院 程 序 设 计 类 课 程 均 采 用 平 时 成 绩 、 实 验 项 目 、 期 末 考 试 等 与 期 末 上 机 考 试 相 结 合 的 考 核 模 式 , 其 中 上 机<br />

考 试 采 用 ACM/ICPC 竞 赛 模 式 , 基 于 Sicily 在 线 测 试 平 台 进 行 , 自 动 提 交 、 自 动 批 改 、 自 动 排 名 , 并 基 于<br />

排 名 给 出 成 绩 。<br />

程 序 设 计 (I) 机 试 占 总 评 成 绩 40%, 机 试 成 绩 不 及 格 者 , 总 评 成 绩 不 得 评 为 及 格 或 以 上 成 绩 。<br />

【Sicily 在 线 评 测 平 台 】<br />

Sicily 在 线 评 测 平 台 网 址 : http://soj.me/<br />

注 意 : 该 平 台 已 有 题 目 大 部 分 是 针 对 ACM/ICPC 训 练 的 , 有 一 定 难 度 , 同 学 们 可 根 据 自 身 能 力 选 择 去 做 。<br />

用 于 课 程 平 时 训 练 及 考 前 训 练 的 题 目 , 任 课 教 师 和 TA 会 给 出 。<br />

【 当 堂 完 成 】<br />

(1) 1000. A-B http://soj.me/1000<br />

(2) 1144. 陶 陶 摘 苹 果 http://soj.me/1144<br />

注 意 : 网 页 上 language 项 , 请 选 GNU C。<br />

【sicily 提 交 返 回 结 果 说 明 】<br />

1 Accepted: 题 目 通 过 测 试 ! 恭 喜 答 对 了 !<br />

2 Presentation Error: 输 出 格 式 错 误 , 离 Accepted 仅 有 一 步 之 遥 。 此 时 应 该 检 查 程 序 输 出 格 式 与 题 目 要 求<br />

输 出 格 式 的 差 别 , 比 如 空 格 、 换 行 等 。 输 入 输 出 格 式 与 要 求 完 全 一 致 , 系 统 才 会 “Accept”。<br />

3 Wrong Answer: 测 试 结 果 错 误 , 检 查 你 的 代 码 。<br />

4 Runtime Error: 程 序 运 行 时 错 , 通 常 是 因 非 法 调 用 、 数 组 或 指 针 越 界 、 溢 出 、 除 数 为 0 等 问 题 引 起 。<br />

5 Compile Error: 编 译 错 误 , 请 检 查 language 项 是 否 选 对 。 建 议 在 dev-c++ 或 其 他 编 程 工 具 中 编 写 程 序 ,<br />

没 有 错 误 , 编 译 通 过 后 再 拷 贝 粘 贴 在 网 页 上 提 交 (Submit), 而 不 是 直 接 在 网 页 上 写 程 序 直 接 提 交 。<br />

6 Time Limit Exceed: 程 序 运 行 超 时 。 检 查 程 序 是 否 有 死 循 环 等 。 复 杂 题 目 则 可 能 还 须 优 化 程 序 效 率 。<br />

7 Memory Limit Exceed: 程 序 运 行 内 存 超 过 限 制 。 此 问 题 较 少 出 现 。 并 且 C 语 言 考 试 基 本 没 有 时 空 限 制 。<br />

8 Restricted Function: 程 序 使 用 了 受 系 统 限 制 的 函 数 , 如 文 件 读 写 函 数 。( 有 时 Runtime Error 也 会 被 判 为<br />

Restricted Function。)<br />

- 8 -


实 验 6<br />

switch 选 择 结 构 练 习<br />

1. 下 面 的 程 序 , 按 颜 色 代 码 和 颜 色 名 称 的 对 应 关 系 , 根 据 输 入 的 颜 色 号 , 输 出 对 应 的 颜 色 名 称 :<br />

0 -- Black , 1 -- Blue , 2 -- Green , 3 -- Red , 4 -- Yellow<br />

#include<br />

int main()<br />

{<br />

int color; /* 用 整 型 数 表 示 颜 色 号 */<br />

printf("Enter color number: ");<br />

scanf("%d",&color);<br />

switch (color)<br />

{<br />

case 0: printf(" Black\n");<br />

break;<br />

case 1: printf(" Blue\n");<br />

break;<br />

case 2: printf(" Green\n");<br />

break;<br />

case 3: printf(" Red\n");<br />

break;<br />

case 4: printf(" Yellow\n");<br />

break;<br />

default: printf(" Error Input\n");<br />

}<br />

return 0;<br />

}<br />

(1) 运 行 程 序 , 使 用 debug 功 能 ( 注 意 toggle breakpoint,run to cursor, next step, 以 及 add watch 等 常 用<br />

功 能 的 使 用 ), 查 看 程 序 执 行 过 程 。 体 会 break 语 句 的 作 用 。 去 掉 若 干 个 break 语 句 , 观 察 运 行 结 果 有<br />

什 么 变 化 。<br />

(2) 将 程 序 结 构 改 为 嵌 套 if 结 构 , 上 交 程 序 。<br />

2. scanf 函 数 输 入 一 个 百 分 制 成 绩 , 输 出 成 绩 等 级 A、B、C、D、E, 其 中 90~100 分 为 A,80~89 分 为 B,<br />

70~79 分 为 C,60~69 分 为 D ,60 分 以 下 分 为 E。<br />

要 求 百 分 制 成 绩 用 整 数 输 入 , 在 输 入 前 要 有 提 示 , 输 入 后 要 判 断 成 绩 的 合 理 性 , 对 不 合 理 的 成 绩 , 应 输<br />

出 出 错 信 息 。 输 出 结 果 中 应 包 括 百 分 制 和 等 级 成 绩 , 并 要 有 文 字 说 明 。 使 用 if 语 句 和 switch 语 句 分 别 实<br />

现 。 得 分 的 数 据 类 型 是 整 型 。<br />

(1) 画 出 程 序 流 程 图 。<br />

(2) 按 要 求 编 写 C 程 序 , 并 在 实 验 报 告 中 分 别 贴 图 显 示 当 分 数 为 59,89,99 时 程 序 的 运 行 的 结 果 。<br />

- 9 -


实 验 7 循 环 结 构 程 序 设 计 (I)<br />

1. 菲 波 那 契 数 列<br />

1, 1, 2, 3, 5, 8, 13, 21…… 为 菲 波 拉 契 数 列 (Fibonacci Sequence), 该 数 列 从 第 3 项 开 始 , 每 项 都 可 表 示 成 前<br />

2 项 的 和 , 即 :F(i)=F(i-1)+F(i-2),i>=3。 编 程 计 算 前 n 项 的 值 。<br />

输 入 : 一 个 正 整 数 n<br />

输 出 : 菲 波 那 契 数 列 前 n 项 的 值 , 值 间 用 逗 号 加 一 个 空 格 隔 开 。<br />

输 入 样 例 :10<br />

输 出 样 例 :1, 1, 2, 3, 5, 8, 13, 21, 34, 55<br />

思 考 :<br />

任 何 数 据 类 型 都 有 表 达 的 范 围 与 界 限 限 制 , 比 如 short, 短 整 数 类 型 , 占 2 个 字 节 , 取 值 范 围 是 -32768 到<br />

32767。 菲 波 那 契 数 列 增 长 很 快 , 如 果 用 short 表 达 , 那 么 只 能 正 确 计 算 得 到 前 23 项 的 值 , 因 为 F(23)=28657,<br />

而 F(24)=46368) 已 越 界 。 思 考 一 下 , 你 所 选 的 数 据 类 型 , 最 多 能 正 确 计 算 多 少 项 <br />

2. 百 钱 百 鸡<br />

一 只 公 鸡 值 五 文 钱 ; 一 只 母 鸡 值 三 文 钱 ; 三 只 小 鸡 值 一 文 钱 。 请 问 用 一 百 文 钱 买 一 百 只 鸡 , 公 鸡 、 母 鸡 和<br />

小 鸡 各 有 几 只 <br />

程 序 无 输 入 , 输 出 所 有 可 能 的 买 3 种 鸡 的 数 目 组 合 , 注 意 边 界 情 况 , 如 不 买 某 一 种 ( 购 买 0 只 )。<br />

3. 借 书<br />

小 明 有 五 本 新 书 , 要 借 给 A,B,C 三 位 小 朋 友 , 若 每 人 每 次 只 能 借 一 本 , 试 编 写 程 序 , 计 算 有 多 少 种 不<br />

同 的 借 法 并 输 出 这 些 借 法 。<br />

程 序 无 输 入 , 输 出 第 一 行 是 共 多 少 种 借 法 , 从 第 二 行 开 始 输 出 所 有 可 能 的 借 法 , 每 种 占 一 行 。<br />

- 10 -


实 验 8 循 环 结 构 程 序 设 计 (II)<br />

1. Sicily 1510. Misspelling http://soj.me/1510<br />

2. 数 列 求 和 。<br />

编 程 求 解 1 2 +2 2 +...+n 2 的 值 。 要 求 分 别 用 while 循 环 、for 循 环 和 do_while 循 环 实 现 。<br />

输 入 : 一 个 正 整 数 n<br />

输 出 : 数 列 的 和 。<br />

输 入 样 例 :5<br />

输 出 样 例 :55<br />

3. 求 平 均 分<br />

编 程 求 解 一 个 小 班 同 学 的 测 验 平 均 分 , 得 分 为 0 到 100 之 间 的 整 数 , 由 于 可 能 有 同 学 请 假 等 原 因 , 出 席 同 学 人<br />

数 不 定 , 输 入 以 -1 作 为 结 束 。 求 解 平 均 数 , 保 留 1 位 小 数 输 出 。<br />

输 入 样 例 :60 90 88 73 -1<br />

输 出 样 例 :77.8<br />

- 11 -


实 验 9 函 数 与 模 块 化 程 序 设 计 (I)<br />

1. 素 数 (prime number)<br />

数 学 上 , 素 数 ( 又 称 质 数 ) 指 的 是 一 个 大 于 1 的 自 然 数 , 除 了 1 和 此 整 数 自 身 外 , 没 法 被 其 他 自 然 数<br />

整 除 的 数 。 即 素 数 只 有 两 个 正 因 数 :1 和 自 身 。<br />

设 计 一 个 判 别 素 数 的 函 数 , 在 主 函 数 中 输 入 一 个 整 数 , 调 用 这 个 判 别 函 数 , 并 输 出 是 否 为 素 数 的 信 息<br />

(“ ** is a prime number.”, or “** is not a prime number.”)。 请 在 实 验 报 告 中 分 别 贴 图 显 示 当 输 入 为 1,2,<br />

14,99,10001 时 程 序 的 运 行 的 结 果 。<br />

注 意 编 程 规 范 , 为 判 别 函 数 和 变 量 取 有 意 义 、 易 理 解 的 名 字 。<br />

2. 阶 乘 n!<br />

n 的 阶 乘 (factorial) 可 表 示 为 f(n) = n! = n*(n-1)*(n-2)*…*2*1.<br />

请 编 写 两 个 函 数 , 分 别 用 递 归 和 非 递 归 两 种 方 法 求 n!, 在 主 函 数 中 输 入 一 个 整 数 n, 分 别 调 用 这 两 个 函 数 ,<br />

测 试 函 数 是 否 正 确 。<br />

3. 公 式 计 算<br />

编 程 计 算 下 面 的 公 式 并 输 出 结 果 :<br />

C m n<br />

n!<br />

=<br />

( n − m)!<br />

m!<br />

编 写 主 函 数 , 由 键 盘 输 入 n 和 m, 调 用 第 二 题 中 实 现 的 一 个 函 数 完 成 计 算 。<br />

输 入 n 和 m 要 给 出 提 示 , 并 检 查 n 和 m 的 合 理 性 , 不 合 理 的 输 入 应 输 出 错 误 信 息 , 并 不 再 进 行 计 算 。<br />

实 验 报 告 中 分 别 贴 图 显 示 当 输 入 为 : m=5,n=8; m=5, n=1; m=0, n=8; m=8,n=8 这 4 组 数 据 时 的 结 果 。<br />

- 12 -


实 验 10 函 数 与 模 块 化 程 序 设 计 (II)<br />

1. 最 大 公 约 数<br />

如 果 有 一 个 自 然 数 a 能 被 自 然 数 b 整 除 , 则 称 a 为 b 的 倍 数 ,b 为 a 的 约 数 。 几 个 自 然 数 公 有 的 约 数 ,<br />

叫 做 这 几 个 自 然 数 的 公 约 数 。 公 约 数 中 最 大 的 一 个 公 约 数 , 称 为 这 几 个 自 然 数 的 最 大 公 约 数 (greatest<br />

common divisor, gcd)。 例 : 在 2、4、6 中 ,2 就 是 2,4,6 的 最 大 公 约 数 。<br />

最 大 公 约 数 满 足 :<br />

gcd( m,<br />

n)<br />

= gcd( m − n,<br />

n),<br />

如 m > n;<br />

gcd( m,<br />

n)<br />

= gcd( m,<br />

n − m),<br />

如 m < n,<br />

gcd( m,<br />

n)<br />

= m,<br />

如 m = n<br />

请 分 别 编 写 2 个 函 数 , 用 递 归 和 非 递 归 两 种 方 法 求 两 个 自 然 数 的 最 大 公 约 数 。<br />

2. 反 序 输 出<br />

将 一 个 正 整 数 n 以 相 反 的 顺 序 输 出 的 递 归 算 法 的 伪 代 码 (Pseudocode) 可 以 描 述 如 下 :<br />

If 要 输 出 的 整 数 只 有 一 位<br />

Then 输 出 该 整 数<br />

Else 输 出 整 数 的 个 位 数 字<br />

反 向 输 出 除 个 位 以 外 的 全 部 数 字<br />

End<br />

请 编 写 一 个 函 数 void printn(int n) 实 现 以 上 为 代 码 , 并 编 写 主 函 数 调 用 该 函 数 测 试 实 现 是 否 正 确 。<br />

输 入 样 例 :1234<br />

输 出 样 例 :4321<br />

- 13 -


实 验 11 数 组 程 序 设 计 (I)<br />

1. 整 数 数 组 排 序<br />

编 写 排 序 函 数 void sort(int a[], int method), 其 中 method=1 表 示 冒 泡 法 ,method=2 表 示 选 择 法 , 具 体 使 用<br />

方 法 由 用 户 在 主 函 数 中 输 入 选 择 。<br />

主 函 数 中 对 数 组 初 始 化 , 测 试 数 据 为 {16,5,8,12,1,17,3,6,10,2}, 然 后 调 用 用 户 指 定 方 法 进 行<br />

排 序 。 要 求 分 别 输 出 排 序 前 和 排 序 后 数 组 元 素 的 值 。<br />

2. 字 符 统 计<br />

对 输 入 一 个 字 符 串 , 统 计 此 字 符 串 中 字 母 (a-z, A-Z)、 数 字 (0-9)、 空 格 (‘ ’), 和 其 它 字 符 的 个 数 , 输 出 四<br />

类 字 符 的 个 数 。 字 符 串 以 回 车 来 结 束 输 入 , 回 车 不 纳 入 统 计 , 要 求 能 处 理 空 串 。<br />

输 入 样 例 :<br />

a1 b2 c3,d4.<br />

输 出 样 例 :<br />

TYPE<br />

No.<br />

Letter 4<br />

Num 4<br />

Space 2<br />

Others 2<br />

3. 二 维 数 组 操 作<br />

主 函 数 中 声 明 一 个 二 维 数 组 A[5][5], 用 随 机 数 函 数 给 其 赋 值 ( 使 用 srand 和 rand 函 数 , 注 意 不 能 从 键 盘 输<br />

入 ,srand/rand 函 数 的 使 用 可 参 考 教 材 156 页 )。 分 别 编 写 3 个 函 数 , 实 现 以 下 功 能 :<br />

(1) 矩 阵 输 出 函 数 , 按 5 行 输 出 , 每 行 5 个 数 据 。<br />

(2) 输 出 其 中 最 大 和 最 小 的 元 素 值 及 位 置 ( 行 号 、 列 号 ) 的 函 数 ;<br />

注 意 : 不 能 把 数 组 元 素 先 排 序 然 后 再 输 出 两 个 数 。<br />

(3) 排 序 函 数 , 将 其 所 有 元 素 排 序 后 从 小 到 大 按 照 A[0][0],A[0][1],…,A[0][4],A[1][0],…,A[4][4]<br />

顺 序 存 放 。<br />

主 函 数 调 用 此 函 数 后 , 再 次 调 用 (1) 中 的 输 出 函 数 , 看 是 否 排 列 正 确 。<br />

- 14 -


实 验 12 数 组 程 序 设 计 (II)<br />

1. Sicily 1341. 明 明 的 随 机 数 http://soj.me/1341<br />

注 意 , 输 入 以 EOF 结 尾 。<br />

2. 奇 偶 分 开<br />

试 编 写 程 序 , 把 给 定 的 数 组 A[N] 中 的 所 有 奇 数 移 到 所 有 偶 数 左 边 。<br />

思 考 如 何 用 尽 量 少 的 运 行 时 间 和 尽 量 少 的 存 储 空 间 实 现 该 要 求 。<br />

输 入 样 例 :<br />

A[10] = {16,5,8,12,1,17,3,6,10,2} ( 可 在 主 函 数 中 以 数 组 初 始 化 的 方 式 给 出 )。<br />

输 出 样 例 :<br />

5,1, 3,17, 16,8,12,6,10,2 ( 输 出 根 据 实 现 不 同 可 能 有 多 种 , 只 要 奇 数 在 左 , 偶 数 在 右 即 可 )<br />

3. 二 维 数 组 部 分 元 素 操 作<br />

编 程 计 算 并 输 出 整 数 矩 阵 除 周 边 以 外 各 元 素 之 和 。<br />

假 设 矩 阵 的 维 数 为 7×4 ( 除 去 周 边 即 剩 下 中 间 5×2,10 个 数 据 )。 矩 阵 各 元 素 从 键 盘 输 入 。<br />

注 意 : 键 盘 输 入 的 值 可 以 写 在 记 事 本 里 , 然 后 右 键 输 入 窗 口 标 题 处 , 选 择 编 辑 , 粘 贴 , 这 样 可 以 减 少 调 试 中 反<br />

复 输 入 数 据 。<br />

- 15 -


实 验 13 指 针 程 序 设 计 (I)<br />

1. 分 析 程 序 的 运 行 结 果 :<br />

void sub(int x, int y, int *z)<br />

{<br />

*z=y-x;<br />

}<br />

int main()<br />

{<br />

int a, b, c;<br />

Sub(10, 5, &a);<br />

sub(7, a, &b);<br />

sub(a, b, &c);<br />

Printf(“%4b,%4d,%4d\n”, a,b,c);<br />

}<br />

请 逐 行 分 析 每 次 调 用 sub 后 的 结 果 , 并 仔 细 体 会 指 针 的 作 用 。<br />

2. 指 针 操 作 数 组<br />

编 写 程 序 , 使 用 指 针 实 现 打 印 一 维 数 组 所 有 元 素 的 操 作 , 要 求 从 键 盘 输 入 数 组 的 值 , 以 每 行 4 个 元 素 的 方<br />

式 打 印 。 可 以 以 define 的 方 式 预 留 足 够 的 数 组 大 小 。<br />

样 例 输 入 :5,12,2,6,1,24,15,11,7,3,19,20,13,8<br />

( 整 数 间 以 逗 号 分 隔 , 即 前 面 的 整 数 后 面 的 是 逗 号 , 最 后 一 个 整 数 后 面 是 回 车 符 , 表 示 结 束 )。<br />

样 例 输 出 :<br />

5 12 2 6<br />

1 24 15 11<br />

7 3 19 20<br />

13 8<br />

3. 字 符 串 拷 贝<br />

编 写 两 个 字 符 串 拷 贝 的 函 数 mystrcopy: void mystrcopy(char *from, char *to)。<br />

主 函 数 中 从 键 盘 输 入 两 个 字 符 串 , 分 别 输 出 两 个 字 符 串 。<br />

然 后 调 用 mystrcopy 函 数 实 现 字 符 串 拷 贝 。 再 输 出 拷 贝 结 束 后 两 个 字 符 串 的 内 容 。<br />

要 求 不 允 许 调 用 C 的 字 符 串 函 数 strcpy。<br />

- 16 -


实 验 14 指 针 程 序 设 计 (II)<br />

1. 函 数 指 针<br />

int max(int x, int y)<br />

{<br />

return x>yx:y;<br />

}<br />

int mean(int x, int y)<br />

{<br />

return (x+y)/2;<br />

}<br />

请 设 计 一 个 主 函 数 , 在 主 函 数 中 定 义 一 个 函 数 指 针 , 可 以 指 向 max 和 mean 函 数 。<br />

在 主 函 数 中 读 入 两 个 值 , 用 函 数 指 针 分 别 调 用 max 和 mean, 并 输 出 函 数 返 回 的 值 。<br />

2. 查 找 相 同 元 素<br />

已 知 两 个 从 小 到 大 有 序 的 数 组 , 编 写 函 数 void findsame(int *a, int sizea, int *b, int sizeb) 实 现 查 找 两 个 数 组<br />

中 出 现 的 所 有 相 同 元 素 , 输 出 所 有 相 同 元 素 的 值 和 这 些 元 素 在 数 组 a 中 相 应 的 位 置 下 标 值 , 若 a 中 有 重 复<br />

元 素 与 b 中 某 元 素 相 同 , 则 输 出 重 复 元 素 在 a 中 最 早 出 现 的 位 置 。<br />

输 入 样 例 :int a[8]={1,2,2,3,3,3,4,7}; int b[6]={1,2,3,4,5,6};<br />

输 入 样 例 :<br />

Val Position<br />

1 0<br />

2 1<br />

3 3<br />

4 6<br />

3. 子 串 替 换<br />

编 写 一 个 函 数 int replace(char *source, char *s1,char *s2, int flag), 把 在 串 source 中 与 s1 相 同 的 串 全 部 更 换 成 串<br />

s2,flag 为 大 小 写 敏 感 的 标 志 (flag=1 大 小 写 敏 感 ,flag=0 不 敏 感 ), 函 数 返 回 被 更 换 的 串 的 数 目 。<br />

输 入 样 例 :<br />

source 串 是 I intinINTinTterrificinuIntstudentninth ( 可 从 电 子 版 实 验 手 册 上 拷 贝 ), s1 是 int, s2 串 是 FLOAT<br />

输 出 样 例 :<br />

flag =1( 大 小 写 敏 感 ), 替 换 后 的 串 是 I FLOATinINTinTterrificinuIntstudentnFLOATh<br />

flag=0( 大 小 写 不 敏 感 ), 替 换 后 的 串 是 I FLOATinFLOATFLOATterrificinuFLOATstudentnFLOATh<br />

- 17 -


实 验 15 结 构 与 链 表<br />

1. 结 构 的 使 用<br />

从 键 盘 输 入 5 个 人 的 姓 名 、 年 龄 和 性 别 , 然 后 输 出 。 要 求 分 别 通 过 结 构 指 针 和 结 构 变 量 名 输 出 信 息 。<br />

用 函 数 data_in 实 现 数 据 输 入 , 用 函 数 data_pout 实 现 通 过 结 构 指 针 输 出 结 构 数 据 的 操 作 , 用 函 数 data_nout<br />

实 现 通 过 结 构 变 量 名 输 出 结 构 数 据 的 操 作 。<br />

2. 链 表 操 作<br />

(1) 构 造 一 个 如 下 图 所 示 的 三 个 结 点 的 有 序 链 表<br />

h<br />

10 20 30<br />

NULL<br />

a b c<br />

(2) 顺 序 输 出 链 表 中 各 个 结 点 的 值 ;<br />

(3) 保 持 链 表 升 序 , 分 别 插 入 值 为 5 和 15 两 个 新 结 点 , 顺 序 输 出 新 的 有 序 链 表 ;<br />

(4) 删 除 值 为 20 的 结 点 , 顺 序 输 出 链 表 中 剩 余 的 结 点 值 。<br />

- 18 -


实 验 16 文 件 操 作<br />

1. 给 定 一 个 文 本 文 件 text-in-5.txt, 二 进 制 文 件 binary-in-5.dat, 各 包 含 5 个 同 学 的 姓 名 及 分 数 。<br />

文 本 文 件 中 , 对 于 每 个 同 学 , 第 一 行 为 姓 名 , 第 二 行 为 分 数 ( 整 数 )。<br />

二 进 制 文 件 中 , 每 条 学 生 记 录 长 sizeof(struct stu) 个 字 节 。 姓 名 最 长 30 个 字 符 ( 含 结 束 标 识 符 ’\0’), 姓 名<br />

中 有 空 格 ( 如 Li Gang), 分 数 为 整 数 。<br />

现 要 求 分 别 用 从 文 本 文 件 text-in-5.txt 和 二 进 制 文 件 binary-in-5.dat 中 读 取 5 个 同 学 的 信 息 , 按 照 分 数 对 这<br />

10 个 同 学 一 起 排 序 , 然 后 将 排 序 好 的 10 个 记 录 分 别 以 文 本 文 件 形 式 和 二 进 制 方 式 写 到 文 本 文 件<br />

text-out-10.txt 和 二 进 制 文 件 binary-out-10.dat 中 。<br />

text-out-10.txt 格 式 要 求 与 text-in-5.txt 相 同 , 即 对 于 每 个 同 学 , 姓 名 占 一 行 , 分 数 占 一 行 。<br />

Binary-out-10.dat 格 式 要 求 与 binary-in-5.dat 相 同 。<br />

结 构 定 义<br />

struct stu {<br />

};<br />

char name[30];<br />

int grade;<br />

- 19 -


综 合 实 验 一 学 生 成 绩 管 理<br />

【 功 能 描 述 】<br />

请 设 计 一 个 简 化 的 学 生 成 绩 管 理 程 序 。<br />

假 设 每 位 学 生 必 须 完 成 必 修 课 5 门 , 选 修 课 2 门 。<br />

该 程 序 应 该 具 有 下 列 功 能 :<br />

(1) 通 过 键 盘 增 加 某 位 学 生 的 成 绩 信 息 ;<br />

(2) 给 定 学 号 , 显 示 某 位 学 生 的 成 绩 情 况 ;<br />

(3) 给 定 某 个 班 级 的 班 号 , 显 示 该 班 所 有 学 生 成 绩 情 况 ;<br />

(4) 给 定 某 位 学 生 的 学 号 , 查 询 或 修 改 该 学 生 的 成 绩 信 息 ;<br />

(5) 可 以 删 除 某 位 同 学 的 成 绩 信 息 ;<br />

(6) 按 照 某 类 课 程 的 学 分 高 低 进 行 排 序 ;<br />

(7) 提 供 一 些 统 计 各 类 信 息 的 功 能 ;<br />

(8) 学 生 成 绩 信 息 存 放 在 磁 盘 文 件 中<br />

【 题 目 要 求 】<br />

(1) 按 照 分 析 、 设 计 、 编 码 、 调 试 和 测 试 的 软 件 开 发 过 程 完 成 这 个 应 用 程 序 ;<br />

(2) 学 分 信 息 应 该 包 括 学 号 、 姓 名 、 课 程 类 别 、 成 绩 、 学 分 、 必 修 课 成 绩 排 名 、 所 有 课 程 总 排 名 等 ;<br />

(3) 为 各 项 操 作 功 能 设 计 一 个 菜 单 。 应 用 程 序 运 行 后 , 先 显 示 这 个 菜 单 , 然 后 用 户 通 过 菜 单 项 选 择 希 望<br />

进 行 的 操 作 项 目 , 主 要 操 作 确 认 过 程 的 一 些 必 要 提 示 信 息 。<br />

【 输 入 要 求 】<br />

应 用 程 序 运 行 后 , 在 屏 幕 上 显 示 一 个 菜 单 ( 菜 单 显 示 外 观 见 前 面 的 图 示 )。 用 户 可 以 根 据 需 求 , 选 定 相<br />

应 的 操 作 项 目 。 进 入 每 个 操 作 后 , 根 据 应 用 程 序 的 提 示 信 息 , 从 键 盘 输 入 相 应 的 信 息 。<br />

【 输 出 要 求 】<br />

(1) 应 用 程 序 运 行 后 , 要 在 屏 幕 上 显 示 一 个 菜 单 ;<br />

(2) 要 求 用 户 输 入 数 据 时 , 要 给 出 清 晰 、 明 确 的 提 示 信 息 , 包 括 输 入 的 数 据 内 容 、 格 式 及 结 束 方 式 等 。<br />

- 20 -


综 合 实 验 二 21 点 扑 克 牌 游 戏<br />

【 功 能 描 述 】<br />

游 戏 程 序 , 一 个 21 点 扑 克 牌 游 戏 , 你 一 共 可 以 要 5 张 牌 , 但 如 果 拍 得 点 数 之 和 超 过 21, 则 暴 了 , 自 动<br />

出 局 , 在 不 超 过 21 点 的 情 况 下 , 你 与 计 算 机 比 牌 的 点 数 大 小 , 大 者 为 赢 。<br />

【 题 目 要 求 】<br />

(1) 程 序 中 一 共 有 13 张 扑 克 牌 可 以 随 机 抽 取 , 大 于 10 的 点 数 计 半 点 ;<br />

(2) 高 级 玩 家 可 以 查 看 下 一 张 牌 , 按 H 键 , 然 后 要 求 输 入 密 码 , 密 码 正 确 可 以 看 牌 , 并 决 定 是 否 要 牌 ;<br />

(3) 可 以 编 写 作 弊 程 序 , 按 某 一 键 去 查 看 计 算 机 的 牌 面 , 并 根 据 计 算 机 所 得 的 牌 输 入 自 己 想 要 的 牌 ;<br />

(4) 每 次 要 牌 后 可 以 设 定 赔 率 , 即 如 果 开 始 下 的 是 10 元 的 注 , 如 果 牌 好 , 你 可 以 要 求 加 注 , 但 不 能 超<br />

过 拥 有 的 钱 数 。<br />

- 21 -


附 录 一 DEV-C++ 使 用 简 介<br />

C 语 言 有 多 种 编 译 器 , 在 windows 系 列 操 作 系 统 ,UNIX/Linux,Apple 之 Mac 系 列 系 统 等 都 有 相 应 的<br />

C 语 言 编 译 器 可 选 择 使 用 。 主 流 C 编 译 器 包 括 Borland 公 司 的 Turbo C/C++、Corland C++ Builder,Microsoft<br />

公 司 的 Visual C++ 等 , 另 外 , 还 有 免 费 版 的 C 语 言 编 译 器 , 包 括 mingW,gcc,Dev-C++ 等 。<br />

本 手 册 选 择 Dev-C++ 作 为 实 验 工 具 。 因 为 Dev-C++ 是 在 GNU 通 用 公 共 许 可 证 下 发 布 的 自 由 软 件 , 软<br />

件 比 较 小 巧 , 有 方 便 的 可 视 化 集 成 开 发 环 境 , 可 以 单 独 编 译 一 个 C 文 件 , 无 须 建 立 工 程 , 对 C 语 言 初 学 者<br />

非 常 友 好 。<br />

以 下 以 如 何 在 Dev-C++ 中 编 写 运 行 “Hello world!” 程 序 为 例 , 演 示 Dev C++ 的 使 用 。<br />

(1) 开 始 - 程 序 -Bloodshed Dev-C++ 打 开 Dev-C++ 集 成 开 发 环 境 , 看 到 如 下 界 面 :<br />

图 1-a<br />

装 好 之 后 菜 单 显 示 默 认 为 英 文 , 从 菜 单 栏 Tools → Environment Options → Interface →Language →<br />

Chinese, 如 图 1-b 所 示 , 可 将 界 面 设 置 为 中 文 。<br />

- 22 -


图 1-b<br />

(2) 选 择 File → New → Source File 建 立 一 个 新 的 源 文 件 , 如 图 2-a 所 示 , 文 件 名 默 认 为 Untitled1。<br />

图 2-a<br />

可 现 在 将 该 文 件 , 或 者 稍 后 将 该 文 件 存 储 为 HelloWorld.c ( 注 意 C 源 程 序 的 文 件 后 缀 .c, 如 图 3-b 所 示 )。<br />

- 23 -


图 2-b<br />

和 其 他 文 件 一 样 ,C 程 序 文 件 可 以 在 下 拉 菜 单 中 选 择 存 储 的 位 置 , 由 于 实 验 室 的 机 器 有 还 原 卡 , 重 启 后 系<br />

统 盘 的 用 户 文 件 将 丢 失 , 所 以 不 建 议 存 储 在 桌 面 或 者 我 的 文 档 中 , 而 建 议 在 D 盘 、E 盘 或 者 是 自 己 的 U 盘<br />

位 置 建 立 相 应 的 文 件 夹 , 存 储 。 最 好 是 用 u 盘 , 这 样 方 便 整 理 和 长 期 存 档 。 使 用 注 意 不 要 染 毒 , 损 害 实 验<br />

室 系 统 。<br />

(3) 在 编 辑 区 中 输 入 一 个 完 整 的 C 程 序 , 如 图 3 所 示 。<br />

图 3<br />

- 24 -


(4) 选 择 Execute → Complie( 如 图 4-a 所 示 ), 或 按 彩 色 田 字 形 compile 按 钮 ( 如 图 4-b 所 示 ) , 对 C 源 程<br />

序 进 行 编 译 :<br />

图 4-a<br />

图 4-b<br />

如 果 程 序 正 确 通 过 编 译 , 则 会 出 现 图 4-c 的 对 话 框 , 按 close 关 闭 。<br />

图 4-c<br />

如 果 有 错 的 话 , 如 printf 行 少 一 个 分 号 , 输 出 框 内 会 有 错 误 提 示 , 如 图 4-d 所 示 :<br />

- 25 -


图 4-d<br />

错 误 信 息 提 示 在 第 7 行 ,system 之 前 有 语 法 错 误 。<br />

在 文 件 编 辑 区 内 对 修 改 源 程 序 , 重 复 编 译 , 直 到 正 确 通 过 编 译 。<br />

(5) 编 译 通 过 后 , 打 开 文 件 存 储 文 件 夹 , 可 发 现 Dev-C++ 帮 我 们 自 动 生 成 了 与 c 源 程 序 同 名 的 exe 可 执 行<br />

文 件 :HelloWorld.exe( 如 图 5-a 所 示 )。<br />

图 5-a<br />

选 择 Execute → run, 或 者 直 接 双 击 HelloWorld.exe 文 件 , 即 可 查 看 程 序 运 行 结 果 , 如 图 5-b 所 示 。<br />

- 26 -


图 5-b<br />

到 这 里 我 们 就 完 成 了 简 单 的 Hello world 程 序 的 编 写 和 运 行 过 程 。<br />

当 然 , 建 立 一 个 程 序 , 尤 其 是 大 程 序 , 往 往 还 有 很 多 其 它 的 事 情 要 做 , 以 上 只 是 一 个 最 基 本 的 过 程 。 比 如<br />

我 们 可 能 需 要 打 开 如 5-c 所 示 的 程 序 调 试 菜 单 选 择 相 应 功 能 进 行 程 序 的 调 试 。<br />

图 5-c<br />

- 27 -


附 录 二 程 序 模 板 示 例<br />

写 程 序 请 注 意 养 成 良 好 的 编 程 习 惯 , 符 合 编 程 规 范 , 代 码 模 板 示 例 如 下 :<br />

/**<br />

* .c Version <br />

*<br />

* Copyright(C) 2009-2010 (SNO: ). All rights reserved.<br />

* is a student majoring in Software Engineering, from the School of Software,<br />

* SUN YAT-SEN UNIVERSITY, GZ 510006, P. R. China.<br />

*/<br />

#include <br />

#include ...<br />

#define ...<br />

/**<br />

* Please put these comments before each function. Give a brief description of the<br />

* function of myFunction(). Then comment the formal parameters and return value<br />

* as the following:<br />

*<br />

* @param firstArg .<br />

* @param secondArg .<br />

* @return .<br />

*/<br />

int myFunction(int firstArg, double secondArg);<br />

- 28 -


附 录 三 C 标 准 库 函 数 ( 摘 自 K&R,The C Programming Language)<br />

This appendix is a summary of the library defined by the ANSI standard. The standard library is not<br />

part of the C language proper, but an environment that supports standard C will provide the function<br />

declarations and type and macro definitions of this library. We have omitted a few functions that are<br />

of limited utility or easily synthesized from others; we have omitted multi-byte characters; and we<br />

have omitted discussion of locale issues; that is, properties that depend on local language,<br />

nationality, or culture.<br />

The functions, types and macros of the standard library are declared in standard headers:<br />

<br />

<br />

<br />

A header can be accessed by<br />

#include <br />

Headers may be included in any order and any number of times. A header must be included outside<br />

of any external declaration or definition and before any use of anything it declares. A header need<br />

not be a source file.<br />

External identifiers that begin with an underscore are reserved for use by the library, as are all other<br />

identifiers that begin with an underscore and an upper-case letter or another underscore.<br />

1 Input and Output: <br />

The input and output functions, types, and macros defined in represent nearly one third of the library.<br />

A stream is a source or destination of data that may be associated with a disk or other peripheral.<br />

The library supports text streams and binary streams, although on some systems, notably UNIX,<br />

these are identical. A text stream is a sequence of lines; each line has zero or more characters and is<br />

terminated by '\n'. An environment may need to convert a text stream to or from some other<br />

representation (such as mapping '\n' to carriage return and linefeed). A binary stream is a sequence<br />

of unprocessed bytes that record internal data, with the property that if it is written, then read back<br />

on the same system, it will compare equal.<br />

A stream is connected to a file or device by opening it; the connection is broken by closing the<br />

stream. Opening a file returns a pointer to an object of type FILE, which records whatever<br />

information is necessary to control the stream. We will use ``file pointer'' and ``stream''<br />

interchangeably when there is no ambiguity.<br />

- 29 -


When a program begins execution, the three streams stdin, stdout, and stderr are already open.<br />

1.1 File Operations<br />

The following functions deal with operations on files. The type size_t is the unsigned integral type produced by<br />

the sizeof operator.<br />

FILE *fopen(const char *filename, const char *mode)<br />

fopen opens the named file, and returns a stream, or NULL if the attempt fails. Legal values for mode<br />

include:<br />

"r"<br />

"w"<br />

"a"<br />

"r+"<br />

"w+"<br />

"a+"<br />

open text file for reading<br />

create text file for writing; discard previous contents if any<br />

append; open or create text file for writing at end of file<br />

open text file for update (i.e., reading and writing)<br />

create text file for update, discard previous contents if any<br />

append; open or create text file for update, writing at end<br />

Update mode permits reading and writing the same file; fflush or a file-positioning function must be<br />

called between a read and a write or vice versa. If the mode includes b after the initial letter, as in "rb" or<br />

"w+b", that indicates a binary file. Filenames are limited to FILENAME_MAX characters. At most<br />

FOPEN_MAX files may be open at once.<br />

FILE *freopen(const char *filename, const char *mode, FILE *stream)<br />

freopen opens the file with the specified mode and associates the stream with it. It returns stream, or<br />

NULL if an error occurs. freopen is normally used to change the files associated with stdin, stdout, or<br />

stderr.<br />

int fflush(FILE *stream)<br />

On an output stream, fflush causes any buffered but unwritten data to be written; on an input stream, the<br />

effect is undefined. It returns EOF for a write error, and zero otherwise. fflush(NULL) flushes all<br />

output streams.<br />

int fclose(FILE *stream)<br />

fclose flushes any unwritten data for stream, discards any unread buffered input, frees any automatically<br />

allocated buffer, then closes the stream. It returns EOF if any errors occurred, and zero otherwise.<br />

int remove(const char *filename)<br />

remove removes the named file, so that a subsequent attempt to open it will fail. It returns non-zero if<br />

the attempt fails.<br />

int rename(const char *oldname, const char *newname)<br />

rename changes the name of a file; it returns non-zero if the attempt fails.<br />

FILE *tmpfile(void)<br />

tmpfile creates a temporary file of mode "wb+" that will be automatically removed when closed or<br />

when the program terminates normally. tmpfile returns a stream, or NULL if it could not create the file.<br />

char *tmpnam(char s[L_tmpnam])<br />

tmpnam(NULL) creates a string that is not the name of an existing file, and returns a pointer to an<br />

internal static array. tmpnam(s) stores the string in s as well as returning it as the function value; s must<br />

- 30 -


have room for at least L_tmpnam characters. tmpnam generates a different name each time it is called;<br />

at most TMP_MAX different names are guaranteed during execution of the program. Note that<br />

tmpnam creates a name, not a file.<br />

int setvbuf(FILE *stream, char *buf, int mode, size_t size)<br />

setvbuf controls buffering for the stream; it must be called before reading, writing or any other operation.<br />

A mode of _IOFBF causes full buffering, _IOLBF line buffering of text files, and _IONBF no<br />

buffering. If buf is not NULL, it will be used as the buffer, otherwise a buffer will be allocated. size<br />

determines the buffer size. setvbuf returns non-zero for any error.<br />

void setbuf(FILE *stream, char *buf)<br />

If buf is NULL, buffering is turned off for the stream. Otherwise, setbuf is equivalent to (void)<br />

setvbuf(stream, buf, _IOFBF, BUFSIZ).<br />

1.2 Formatted Output<br />

The printf functions provide formatted output conversion.<br />

int fprintf(FILE *stream, const char *format, ...)<br />

fprintf converts and writes output to stream under the control of format. The return value is the number of<br />

characters written, or negative if an error occurred.<br />

The format string contains two types of objects: ordinary characters, which are copied to the output<br />

stream, and conversion specifications, each of which causes conversion and printing of the next<br />

successive argument to fprintf. Each conversion specification begins with the character % and ends<br />

with a conversion character. Between the % and the conversion character there may be, in order:<br />

• Flags (in any order), which modify the specification:<br />

o -, which specifies left adjustment of the converted argument in its field.<br />

o +, which specifies that the number will always be printed with a sign.<br />

o space: if the first character is not a sign, a space will be prefixed.<br />

o 0: for numeric conversions, specifies padding to the field width with leading zeros.<br />

o #, which specifies an alternate output form. For o, the first digit will become zero. For x or X,<br />

0x or 0X will be prefixed to a non-zero result. For e, E, f, g, and G, the output will always have<br />

a decimal point; for g and G, trailing zeros will not be removed.<br />

• A number specifying a minimum field width. The converted argument will be printed in a field at least<br />

this wide, and wider if necessary. If the converted argument has fewer characters than the field width it<br />

will be padded on the left (or right, if left adjustment has been requested) to make up the field width. The<br />

padding character is normally space, but is 0 if the zero padding flag is present.<br />

• A period, which separates the field width from the precision.<br />

• A number, the precision, that specifies the maximum number of characters to be printed from a string, or<br />

the number of digits to be printed after the decimal point for e, E, or f conversions, or the number of<br />

significant digits for g or G conversion, or the number of digits to be printed for an integer (leading 0s<br />

will be added to make up the necessary width).<br />

- 31 -


• A length modifier h, l (letter ell), or L. ``h'' indicates that the corresponding argument is to be printed as a<br />

short or unsigned short; ``l'' indicates that the argument is a long or unsigned long, ``L'' indicates<br />

that the argument is a long double.<br />

Width or precision or both may be specified as *, in which case the value is computed by<br />

converting the next argument(s), which must be int.<br />

The conversion characters and their meanings are shown in Table 1. If the character after the % is<br />

not a conversion character, the behavior is undefined.<br />

Table 1 Printf Conversions<br />

Character<br />

Argument type; Printed As<br />

d,i<br />

o<br />

x,X<br />

u<br />

c<br />

s<br />

f<br />

e,E<br />

g,G<br />

p<br />

n<br />

int; signed decimal notation.<br />

int; unsigned octal notation (without a leading zero).<br />

unsigned int; unsigned hexadecimal notation (without a leading 0x or 0X), using abcdef for<br />

0x or ABCDEF for 0X.<br />

int; unsigned decimal notation.<br />

int; single character, after conversion to unsigned char<br />

char *; characters from the string are printed until a '\0' is reached or until the number of<br />

characters indicated by the precision have been printed.<br />

double; decimal notation of the form [-]mmm.ddd, where the number of d's is given by the<br />

precision. The default precision is 6; a precision of 0 suppresses the decimal point.<br />

double; decimal notation of the form [-]m.dddddde+/-xx or [-]m.ddddddE+/-xx, where the<br />

number of d's is specified by the precision. The default precision is 6; a precision of 0 suppresses<br />

the decimal point.<br />

double; %e or %E is used if the exponent is less than -4 or greater than or equal to the<br />

precision; otherwise %f is used. Trailing zeros and a trailing decimal point are not printed.<br />

void *; print as a pointer (implementation-dependent representation).<br />

int *; the number of characters written so far by this call to printf is written into the argument.<br />

No argument is converted.<br />

% no argument is converted; print a %<br />

int printf(const char *format, ...)<br />

printf(...) is equivalent to fprintf(stdout, ...).<br />

int sprintf(char *s, const char *format, ...)<br />

sprintf is the same as printf except that the output is written into the string s, terminated with '\0'. s must<br />

be big enough to hold the result. The return count does not include the '\0'.<br />

int vprintf(const char *format, va_list arg)<br />

int vfprintf(FILE *stream, const char *format, va_list arg)<br />

int vsprintf(char *s, const char *format, va_list arg)<br />

- 32 -


The functions vprintf, vfprintf, and vsprintf are equivalent to the corresponding printf functions,<br />

except that the variable argument list is replaced by arg, which has been initialized by the va_start<br />

macro and perhaps va_arg calls. See the discussion of in Section 7.<br />

1.3 Formatted Input<br />

The scanf function deals with formatted input conversion.<br />

int fscanf(FILE *stream, const char *format, ...)<br />

fscanf reads from stream under control of format, and assigns converted values through subsequent arguments,<br />

each of which must be a pointer. It returns when format is exhausted. fscanf returns EOF if end of file or an<br />

error occurs before any conversion; otherwise it returns the number of input items converted and assigned.<br />

The format string usually contains conversion specifications, which are used to direct interpretation<br />

of input. The format string may contain:<br />

• Blanks or tabs, which are not ignored.<br />

• Ordinary characters (not %), which are expected to match the next non-white space character of the input<br />

stream.<br />

• Conversion specifications, consisting of a %, an optional assignment suppression character *, an optional<br />

number specifying a maximum field width, an optional h, l, or L indicating the width of the target, and a<br />

conversion character.<br />

A conversion specification determines the conversion of the next input field. Normally the result is placed in the<br />

variable pointed to by the corresponding argument. If assignment suppression is indicated by *, as in %*s,<br />

however, the input field is simply skipped; no assignment is made. An input field is defined as a string of<br />

non-white space characters; it extends either to the next white space character or until the field width, if specified,<br />

is exhausted. This implies that scanf will read across line boundaries to find its input, since newlines are white<br />

space. (White space characters are blank, tab, newline, carriage return, vertical tab, and formfeed.)<br />

The conversion character indicates the interpretation of the input field. The corresponding argument<br />

must be a pointer. The legal conversion characters are shown in Table 2.<br />

The conversion characters d, i, n, o, u, and x may be preceded by h if the argument is a pointer to<br />

short rather than int, or by l (letter ell) if the argument is a pointer to long. The conversion<br />

characters e, f, and g may be preceded by l if a pointer to double rather than float is in the argument<br />

list, and by L if a pointer to a long double.<br />

Table 2 Scanf Conversions<br />

Character<br />

Input Data; Argument type<br />

d<br />

i<br />

decimal integer; int*<br />

integer; int*. The integer may be in octal (leading 0) or hexadecimal (leading 0x or 0X).<br />

- 33 -


o octal integer (with or without leading zero); int *.<br />

u unsigned decimal integer; unsigned int *.<br />

x<br />

c<br />

s<br />

e,f,g<br />

hexadecimal integer (with or without leading 0x or 0X); int*.<br />

characters; char*. The next input characters are placed in the indicated array, up to the number<br />

given by the width field; the default is 1. No '\0' is added. The normal skip over white space<br />

characters is suppressed in this case; to read the next non-white space character, use %1s.<br />

string of non-white space characters (not quoted); char *, pointing to an array of characters<br />

large enough to hold the string and a terminating '\0' that will be added.<br />

floating-point number; float *. The input format for float's is an optional sign, a string of<br />

numbers possibly containing a decimal point, and an optional exponent field containing an E or<br />

e followed by a possibly signed integer.<br />

p pointer value as printed by printf("%p");, void *.<br />

n<br />

[...]<br />

[^...]<br />

writes into the argument the number of characters read so far by this call; int *. No input is read.<br />

The converted item count is not incremented.<br />

matches the longest non-empty string of input characters from the set between brackets; char *.<br />

A '\0' is added. []...] includes ] in the set.<br />

matches the longest non-empty string of input characters not from the set between brackets;<br />

char *. A '\0' is added. [^]...] includes ] in the set.<br />

% literal %; no assignment is made.<br />

int scanf(const char *format, ...)<br />

scanf(...) is identical to fscanf(stdin, ...).<br />

int sscanf(const char *s, const char *format, ...)<br />

sscanf(s, ...) is equivalent to scanf(...) except that the input characters are taken from the string s.<br />

1.4 Character Input and Output Functions<br />

int fgetc(FILE *stream)<br />

fgetc returns the next character of stream as an unsigned char (converted to an int), or EOF if end of<br />

file or error occurs.<br />

char *fgets(char *s, int n, FILE *stream)<br />

fgets reads at most the next n-1 characters into the array s, stopping if a newline is encountered; the<br />

newline is included in the array, which is terminated by '\0'. fgets returns s, or NULL if end of file or<br />

error occurs.<br />

int fputc(int c, FILE *stream)<br />

fputc writes the character c (converted to an unsigend char) on stream. It returns the character written,<br />

or EOF for error.<br />

int fputs(const char *s, FILE *stream)<br />

fputs writes the string s (which need not contain \n) on stream; it returns non-negative, or EOF for an<br />

error.<br />

int getc(FILE *stream)<br />

- 34 -


getc is equivalent to fgetc except that if it is a macro, it may evaluate stream more than once.<br />

int getchar(void)<br />

getchar is equivalent to getc(stdin).<br />

char *gets(char *s)<br />

gets reads the next input line into the array s; it replaces the terminating newline with '\0'. It returns s, or<br />

NULL if end of file or error occurs.<br />

int putc(int c, FILE *stream)<br />

putc is equivalent to fputc except that if it is a macro, it may evaluate stream more than once.<br />

int putchar(int c)<br />

putchar(c) is equivalent to putc(c,stdout).<br />

int puts(const char *s)<br />

puts writes the string s and a newline to stdout. It returns EOF if an error occurs, non-negative<br />

otherwise.<br />

int ungetc(int c, FILE *stream)<br />

ungetc pushes c (converted to an unsigned char) back onto stream, where it will be returned on the<br />

next read. Only one character of pushback per stream is guaranteed. EOF may not be pushed back.<br />

ungetc returns the character pushed back, or EOF for error.<br />

1.5 Direct Input and Output Functions<br />

size_t fread(void *ptr, size_t size, size_t nobj, FILE *stream)<br />

fread reads from stream into the array ptr at most nobj objects of size size. fread returns the number<br />

of objects read; this may be less than the number requested. feof and ferror must be used to determine<br />

status.<br />

size_t fwrite(const void *ptr, size_t size, size_t nobj, FILE *stream)<br />

fwrite writes, from the array ptr, nobj objects of size size on stream. It returns the number of objects<br />

written, which is less than nobj on error.<br />

1.6 File Positioning Functions<br />

int fseek(FILE *stream, long offset, int origin)<br />

fseek sets the file position for stream; a subsequent read or write will access data beginning at the new<br />

position. For a binary file, the position is set to offset characters from origin, which may be<br />

SEEK_SET (beginning), SEEK_CUR (current position), or SEEK_END (end of file). For a text<br />

stream, offset must be zero, or a value returned by ftell (in which case origin must be SEEK_SET).<br />

fseek returns non-zero on error.<br />

long ftell(FILE *stream)<br />

ftell returns the current file position for stream, or -1 on error.<br />

void rewind(FILE *stream)<br />

rewind(fp) is equivalent to fseek(fp, 0L, SEEK_SET); clearerr(fp).<br />

int fgetpos(FILE *stream, fpos_t *ptr)<br />

fgetpos records the current position in stream in *ptr, for subsequent use by fsetpos. The type fpos_t<br />

- 35 -


is suitable for recording such values. fgetpos returns non-zero on error.<br />

int fsetpos(FILE *stream, const fpos_t *ptr)<br />

fsetpos positions stream at the position recorded by fgetpos in *ptr. fsetpos returns non-zero on error.<br />

1.7 Error Functions<br />

Many of the functions in the library set status indicators when error or end of file occur. These indicators may be<br />

set and tested explicitly. In addition, the integer expression errno (declared in ) may contain an error<br />

number that gives further information about the most recent error.<br />

void clearerr(FILE *stream)<br />

clearerr clears the end of file and error indicators for stream.<br />

int feof(FILE *stream)<br />

feof returns non-zero if the end of file indicator for stream is set.<br />

int ferror(FILE *stream)<br />

ferror returns non-zero if the error indicator for stream is set.<br />

void perror(const char *s)<br />

perror(s) prints s and an implementation-defined error message corresponding to the integer in errno, as<br />

if by<br />

fprintf(stderr, "%s: %s\n", s, "error message");<br />

See strerror in Section 3.<br />

2 Character Class Tests: <br />

The header declares functions for testing characters. For each function, the argument list is an int,<br />

whose value must be EOF or representable as an unsigned char, and the return value is an int. The functions<br />

return non-zero (true) if the argument c satisfies the condition described, and zero if not.<br />

isalnum(c)<br />

isalpha(c)<br />

iscntrl(c)<br />

isdigit(c)<br />

isgraph(c)<br />

islower(c)<br />

isprint(c)<br />

ispunct(c)<br />

isspace(c)<br />

isupper(c)<br />

isxdigit(c)<br />

isalpha(c) or isdigit(c) is true<br />

isupper(c) or islower(c) is true<br />

control character<br />

decimal digit<br />

printing character except space<br />

lower-case letter<br />

printing character including space<br />

printing character except space or letter or digit<br />

space, formfeed, newline, carriage return, tab, vertical tab<br />

upper-case letter<br />

hexadecimal digit<br />

- 36 -


In the seven-bit ASCII character set, the printing characters are 0x20 (' ') to 0x7E ('-'); the control<br />

characters are 0 NUL to 0x1F (US), and 0x7F (DEL).<br />

In addition, there are two functions that convert the case of letters:<br />

int tolower(c)<br />

int toupper(c)<br />

convert c to lower case<br />

convert c to upper case<br />

If c is an upper-case letter, tolower(c) returns the corresponding lower-case letter, toupper(c) returns<br />

the corresponding upper-case letter; otherwise it returns c.<br />

3 String Functions: <br />

There are two groups of string functions defined in the header . The first have names beginning with<br />

str; the second have names beginning with mem. Except for memmove, the behavior is undefined if copying<br />

takes place between overlapping objects. Comparison functions treat arguments as unsigned char arrays.<br />

In the following table, variables s and t are of type char *; cs and ct are of type const char *; n is of<br />

type size_t; and c is an int converted to char.<br />

char *strcpy(s,ct) copy string ct to string s, including '\0'; return s.<br />

char<br />

*strncpy(s,ct,n)<br />

copy at most n characters of string ct to s; return s. Pad with '\0''s if ct has fewer<br />

than n characters.<br />

char *strcat(s,ct) concatenate string ct to end of string s; return s.<br />

char<br />

*strncat(s,ct,n)<br />

int strcmp(cs,ct)<br />

int strncmp(cs,ct,n)<br />

char *strchr(cs,c)<br />

char *strrchr(cs,c)<br />

size_t strspn(cs,ct)<br />

size_t<br />

strcspn(cs,ct)<br />

char *strpbrk(cs,ct)<br />

char *strstr(cs,ct)<br />

size_t strlen(cs)<br />

concatenate at most n characters of string ct to string s, terminate s with '\0'; return<br />

s.<br />

compare string cs to string ct, return ct.<br />

compare at most n characters of string cs to string ct; return ct.<br />

return pointer to first occurrence of c in cs or NULL if not present.<br />

return pointer to last occurrence of c in cs or NULL if not present.<br />

return length of prefix of cs consisting of characters in ct.<br />

return length of prefix of cs consisting of characters not in ct.<br />

return pointer to first occurrence in string cs of any character string ct, or NULL if<br />

not present.<br />

return pointer to first occurrence of string ct in cs, or NULL if not present.<br />

return length of cs.<br />

char *strerror(n) return pointer to implementation-defined string corresponding to error n.<br />

- 37 -


char *strtok(s,ct)<br />

strtok searches s for tokens delimited by characters from ct; see below.<br />

A sequence of calls of strtok(s,ct) splits s into tokens, each delimited by a character from ct. The<br />

first call in a sequence has a non-NULL s, it finds the first token in s consisting of characters not in<br />

ct; it terminates that by overwriting the next character of s with '\0' and returns a pointer to the token.<br />

Each subsequent call, indicated by a NULL value of s, returns the next such token, searching from<br />

just past the end of the previous one. strtok returns NULL when no further token is found. The<br />

string ct may be different on each call.<br />

The mem... functions are meant for manipulating objects as character arrays; the intent is an<br />

interface to efficient routines. In the following table, s and t are of type void *; cs and ct are of type<br />

const void *; n is of type size_t; and c is an int converted to an unsigned char.<br />

void *memcpy(s,ct,n) copy n characters from ct to s, and return s.<br />

void<br />

*memmove(s,ct,n)<br />

int memcmp(cs,ct,n)<br />

void *memchr(cs,c,n)<br />

same as memcpy except that it works even if the objects overlap.<br />

compare the first n characters of cs with ct; return as with strcmp.<br />

return pointer to first occurrence of character c in cs, or NULL if not present<br />

among the first n characters.<br />

void *memset(s,c,n) place character c into first n characters of s, return s.<br />

4 Mathematical Functions: <br />

The header declares mathematical functions and macros.<br />

The macros EDOM and ERANGE (found in ) are non-zero integral constants that are<br />

used to signal domain and range errors for the functions; HUGE_VAL is a positive double value. A<br />

domain error occurs if an argument is outside the domain over which the function is defined. On a<br />

domain error, errno is set to EDOM; the return value is implementation-defined. A range error<br />

occurs if the result of the function cannot be represented as a double. If the result overflows, the<br />

function returns HUGE_VAL with the right sign, and errno is set to ERANGE. If the result<br />

underflows, the function returns zero; whether errno is set to ERANGE is implementation-defined.<br />

In the following table, x and y are of type double, n is an int, and all functions return double. Angles<br />

for trigonometric functions are expressed in radians.<br />

sin(x)<br />

cos(x)<br />

tan(x)<br />

sine of x<br />

cosine of x<br />

tangent of x<br />

asin(x) sin -1 (x) in range [-pi/2,pi/2], x in [-1,1].<br />

acos(x) cos -1 (x) in range [0,pi], x in [-1,1].<br />

- 38 -


atan(x)<br />

atan2(y,x)<br />

sinh(x)<br />

cosh(x)<br />

tanh(x)<br />

exp(x)<br />

log(x)<br />

log10(x)<br />

pow(x,y)<br />

sqrt(x)<br />

ceil(x)<br />

floor(x)<br />

fabs(x)<br />

ldexp(x,n)<br />

frexp(x,<br />

*ip)<br />

modf(x,<br />

double *ip)<br />

fmod(x,y)<br />

int<br />

tan -1 (x) in range [-pi/2,pi/2].<br />

tan -1 (y/x) in range [-pi,pi].<br />

hyperbolic sine of x<br />

hyperbolic cosine of x<br />

hyperbolic tangent of x<br />

exponential function e x<br />

natural logarithm ln(x), x>0.<br />

base 10 logarithm log 10 (x), x>0.<br />

x y . A domain error occurs if x=0 and y


leading 0x or 0X is permitted in base 16. If the answer would overflow, LONG_MAX or<br />

LONG_MIN is returned, depending on the sign of the result, and errno is set to ERANGE.<br />

unsigned long strtoul(const char *s, char **endp, int base)<br />

strtoul is the same as strtol except that the result is unsigned long and the error value is<br />

ULONG_MAX.<br />

int rand(void)<br />

rand returns a pseudo-random integer in the range 0 to RAND_MAX, which is at least 32767.<br />

void srand(unsigned int seed)<br />

srand uses seed as the seed for a new sequence of pseudo-random numbers. The initial seed is 1.<br />

void *calloc(size_t nobj, size_t size)<br />

calloc returns a pointer to space for an array of nobj objects, each of size size, or NULL if the request<br />

cannot be satisfied. The space is initialized to zero bytes.<br />

void *malloc(size_t size)<br />

malloc returns a pointer to space for an object of size size, or NULL if the request cannot be satisfied.<br />

The space is uninitialized.<br />

void *realloc(void *p, size_t size)<br />

realloc changes the size of the object pointed to by p to size. The contents will be unchanged up to the<br />

minimum of the old and new sizes. If the new size is larger, the new space is uninitialized. realloc<br />

returns a pointer to the new space, or NULL if the request cannot be satisfied, in which case *p is<br />

unchanged.<br />

void free(void *p)<br />

free deallocates the space pointed to by p; it does nothing if p is NULL. p must be a pointer to space<br />

previously allocated by calloc, malloc, or realloc.<br />

void abort(void)<br />

abort causes the program to terminate abnormally, as if by raise(SIGABRT).<br />

void exit(int status)<br />

exit causes normal program termination. atexit functions are called in reverse order of registration, open<br />

files are flushed, open streams are closed, and control is returned to the environment. How status is<br />

returned to the environment is implementation-dependent, but zero is taken as successful termination. The<br />

values EXIT_SUCCESS and EXIT_FAILURE may also be used.<br />

int atexit(void (*fcn)(void))<br />

atexit registers the function fcn to be called when the program terminates normally; it returns non-zero if<br />

the registration cannot be made.<br />

int system(const char *s)<br />

system passes the string s to the environment for execution. If s is NULL, system returns non-zero if<br />

there is a command processor. If s is not NULL, the return value is implementation-dependent.<br />

char *getenv(const char *name)<br />

getenv returns the environment string associated with name, or NULL if no string exists. Details are<br />

implementation-dependent.<br />

void *bsearch(const void *key, const void *base,<br />

size_t n, size_t size,<br />

int (*cmp)(const void *keyval, const void *datum))<br />

bsearch searches base[0]...base[n-1] for an item that matches *key. The function cmp must return<br />

negative if its first argument (the search key) is less than its second (a table entry), zero if equal, and<br />

- 40 -


positive if greater. Items in the array base must be in ascending order. bsearch returns a pointer to a<br />

matching item, or NULL if none exists.<br />

void qsort(void *base, size_t n, size_t size,<br />

int (*cmp)(const void *, const void *))<br />

qsort sorts into ascending order an array base[0]...base[n-1] of objects of size size. The comparison<br />

function cmp is as in bsearch.<br />

int abs(int n)<br />

abs returns the absolute value of its int argument.<br />

long labs(long n)<br />

labs returns the absolute value of its long argument.<br />

div_t div(int num, int denom)<br />

div computes the quotient and remainder of num/denom. The results are stored in the int members<br />

quot and rem of a structure of type div_t.<br />

ldiv_t ldiv(long num, long denom)<br />

ldiv computes the quotient and remainder of num/denom. The results are stored in the long members<br />

quot and rem of a structure of type ldiv_t.<br />

6 Diagnostics: <br />

The assert macro is used to add diagnostics to programs:<br />

void assert(int expression)<br />

If expression is zero when<br />

assert(expression)<br />

is executed, the assert macro will print on stderr a message, such as<br />

Assertion failed: expression, file filename, line nnn<br />

It then calls abort to terminate execution. The source filename and line number come from the<br />

preprocessor macros __FILE__ and __LINE__.<br />

If NDEBUG is defined at the time is included, the assert macro is ignored.<br />

7 Variable Argument Lists: <br />

The header provides facilities for stepping through a list of function arguments of unknown number<br />

and type.<br />

Suppose lastarg is the last named parameter of a function f with a variable number of arguments.<br />

Then declare within f a variable of type va_list that will point to each argument in turn:<br />

va_list ap;<br />

ap must be initialized once with the macro va_start before any unnamed argument is accessed:<br />

- 41 -


va_start(va_list ap, lastarg);<br />

Thereafter, each execution of the macro va_arg will produce a value that has the type and value of<br />

the next unnamed argument, and will also modify ap so the next use of va_arg returns the next<br />

argument:<br />

type va_arg(va_list ap, type);<br />

The macro<br />

void va_end(va_list ap);<br />

must be called once after the arguments have been processed but before f is exited.<br />

8 Non-local Jumps: <br />

The declarations in provide a way to avoid the normal function call and return sequence, typically to<br />

permit an immediate return from a deeply nested function call.<br />

int setjmp(jmp_buf env)<br />

The macro setjmp saves state information in env for use by longjmp. The return is zero from a direct<br />

call of setjmp, and non-zero from a subsequent call of longjmp. A call to setjmp can only occur in<br />

certain contexts, basically the test of if, switch, and loops, and only in simple relational expressions.<br />

if (setjmp(env) == 0)<br />

/* get here on direct call */<br />

else<br />

/* get here by calling longjmp */<br />

void longjmp(jmp_buf env, int val)<br />

longjmp restores the state saved by the most recent call to setjmp, using the information saved in env,<br />

and execution resumes as if the setjmp function had just executed and returned the non-zero value val.<br />

The function containing the setjmp must not have terminated. Accessible objects have the values they<br />

had at the time longjmp was called, except that non-volatile automatic variables in the function calling<br />

setjmp become undefined if they were changed after the setjmp call.<br />

9 Signals: <br />

The header provides facilities for handling exceptional conditions that arise during execution, such as<br />

an interrupt signal from an external source or an error in execution.<br />

void (*signal(int sig, void (*handler)(int)))(int)<br />

signal determines how subsequent signals will be handled. If handler is SIG_DFL, the implementation-defined<br />

default behavior is used, if it is SIG_IGN, the signal is ignored; otherwise, the function pointed to by handler<br />

will be called, with the argument of the type of signal. Valid signals include<br />

SIGABRT<br />

SIGFPE<br />

SIGILL<br />

SIGINT<br />

abnormal termination, e.g., from abort<br />

arithmetic error, e.g., zero divide or overflow<br />

illegal function image, e.g., illegal instruction<br />

interactive attention, e.g., interrupt<br />

- 42 -


SIGSEGV<br />

SIGTERM<br />

illegal storage access, e.g., access outside memory limits<br />

termination request sent to this program<br />

signal returns the previous value of handler for the specific signal, or SIG_ERR if an error occurs.<br />

When a signal sig subsequently occurs, the signal is restored to its default behavior; then the<br />

signal-handler function is called, as if by (*handler)(sig). If the handler returns, execution will<br />

resume where it was when the signal occurred.<br />

The initial state of signals is implementation-defined.<br />

int raise(int sig)<br />

raise sends the signal sig to the program; it returns non-zero if unsuccessful.<br />

10 Date and Time Functions: <br />

The header declares types and functions for manipulating date and time. Some functions process local<br />

time, which may differ from calendar time, for example because of time zone. clock_t and time_t are arithmetic<br />

types representing times, and struct tm holds the components of a calendar time:<br />

int tm_sec; seconds after the minute (0,61)<br />

int tm_min; minutes after the hour (0,59)<br />

int tm_hour; hours since midnight (0,23)<br />

int tm_mday; day of the month (1,31)<br />

int tm_mon; months since January (0,11)<br />

int tm_year; years since 1900<br />

int tm_wday; days since Sunday (0,6)<br />

int tm_yday; days since January 1 (0,365)<br />

int tm_isdst;<br />

Daylight Saving Time flag<br />

tm_isdst is positive if Daylight Saving Time is in effect, zero if not, and negative if the information<br />

is not available.<br />

clock_t clock(void)<br />

clock returns the processor time used by the program since the beginning of execution, or -1 if<br />

unavailable. clock()/CLK_PER_SEC is a time in seconds.<br />

time_t time(time_t *tp)<br />

time returns the current calendar time or -1 if the time is not available. If tp is not NULL, the return<br />

value is also assigned to *tp.<br />

double difftime(time_t time2, time_t time1)<br />

difftime returns time2-time1 expressed in seconds.<br />

- 43 -


time_t mktime(struct tm *tp)<br />

mktime converts the local time in the structure *tp into calendar time in the same representation used by<br />

time. The components will have values in the ranges shown. mktime returns the calendar time or -1 if it<br />

cannot be represented.<br />

The next four functions return pointers to static objects that may be overwritten by other calls.<br />

char *asctime(const struct tm *tp)<br />

asctime


%x local date representation.<br />

%X local time representation.<br />

%y year without century (00-99).<br />

%Y year with century.<br />

%Z time zone name, if any.<br />

%% %<br />

11 Implementation-defined Limits: and <br />

The header defines constants for the sizes of integral types. The values below are<br />

acceptable minimum magnitudes; larger values may be used.<br />

CHAR_BIT 8 bits in a char<br />

CHAR_MAX UCHAR_MAX or SCHAR_MAX maximum value of char<br />

CHAR_MIN 0 or SCHAR_MIN maximum value of char<br />

INT_MAX 32767 maximum value of int<br />

INT_MIN -32767 minimum value of int<br />

LONG_MAX 2147483647 maximum value of long<br />

LONG_MIN -2147483647 minimum value of long<br />

SCHAR_MAX +127 maximum value of signed char<br />

SCHAR_MIN -127 minimum value of signed char<br />

SHRT_MAX +32767 maximum value of short<br />

SHRT_MIN -32767 minimum value of short<br />

UCHAR_MAX 255 maximum value of unsigned char<br />

UINT_MAX 65535 maximum value of unsigned int<br />

ULONG_MAX 4294967295 maximum value of unsigned long<br />

USHRT_MAX 65535 maximum value of unsigned short<br />

The names in the table below, a subset of , are constants related to floating-point<br />

arithmetic. When a value is given, it represents the minimum magnitude for the corresponding<br />

quantity. Each implementation defines appropriate values.<br />

FLT_RADIX 2 radix of exponent, representation, e.g., 2, 16<br />

FLT_ROUNDS<br />

floating-point rounding mode for addition<br />

FLT_D IG 6 decimal digits of precision<br />

FLT_EPSILON 1E-5 smallest number x such that 1.0+x != 1.0<br />

FLT_MANT_DIG<br />

number of base FLT_R ADIX in mantissa<br />

- 45 -


FLT_MAX 1E+37 maximum floating-point number<br />

FLT_MAX_EXP<br />

maximum n such that FLT_RADIX n-1 is representable<br />

FLT_M IN 1E-37 minimum normalized floating-point number<br />

FLT_MIN_EXP<br />

minimum n such that 10 n is a normalized number<br />

DBL_DIG 10 decimal digits of precision<br />

DBL_EPSILON 1E-9 smallest number x such that 1.0+x != 1.0<br />

DBL_MANT_DIG<br />

number of base FLT_R ADIX in mantissa<br />

DBL_MAX 1E+37 maximum double floating-point number<br />

DBL_MAX_EXP<br />

maximum n such that FLT_RADIX n-1 is representable<br />

DBL_MIN 1E-37 minimum normalized double floating-point number<br />

DBL_MIN_EXP<br />

minimum n such that 10 n is a normalized number<br />

- 46 -

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!