Tips:"分享是快乐的源泉💧,在我的博客里,不仅有知识的海洋🌊,还有满满的正能量加持💪,快来和我一起分享这份快乐吧😊!
喜欢我的博客的话,记得点个红心❤️和小关小注哦!您的支持是我创作的动力!数据源
存放在我的资源下载区啦!
Linux程序开发(四):IO编程和文件流操作
目录
- Linux程序开发(四):IO编程和文件流操作
- 1. 问答题
- 2. 编程题
- 2.1. 编写程序实现拷贝文件功能,该程序运行时有两个参数,分别为源文件和目标文件,程序能够显示打开、读取、写入、关闭文件操作时的错误。假定编译后的程序名为mycopy,使用方法如:
- 2.2. 编写程序实现删除文件功能,该程序运行时有多个参数,可以删除多个参数代表的文件。
- 2.3. 编程要求:
- 2.4. 编程要求:
- 2.5. 文件IO编程:补全下面代码,从一个文件(源文件)中读取后10KB数据并复制到另一个文件(目标文件)。
- 2.6. 创建新文件aa.txt,内容“Hello World!”,该文件具有用户读写权限。采用fcntl 复制一个新的文件描述符,通过新文件描述符向文件末尾写入“Linux is an open source OS.”字符串。
- 2.7. 编写程序,对未知txt文件word.txt中所有的is修改成are。如果存在is,就进行修改;如果不存在is,就不做修改。
- 2.8. 存在两个txt文件,分别为a.txt与b.txt,a.txt内容为“Captain: Are ya ready kids?” ,b.txt中的内容是“Kids: Aye Aye Captain.”。将a.txt中的内容复制到b.txt中,把b.txt中的内容复制到a.txt中。
1. 问答题
1.1. 硬链接和软链接(符号链接)的区别是?
# 硬链接和软链接(符号链接)是操作系统中用于创建文件链接的两种不同方式。
(1)硬链接:硬链接是通过在文件系统中创建一个新的文件项来实现的,该文件项与原始文件具有相同的索引节点(inode)。硬链接与原始文件共享相同的数据块,因此它们指向相同的物理文件内容。删除原始文件不会影响硬链接的可用性,只有当所有链接都被删除时,才会真正释放文件的存储空间。硬链接只能链接到同一文件系统中的文件。
(2)软链接(符号链接):软链接是一个特殊的文件,它包含指向目标文件或目录的路径。软链接创建了一个新的文件项,该文件项包含指向目标文件的路径信息。与硬链接不同,软链接具有自己的索引节点,并且可以跨越文件系统边界链接到不同的文件。软链接可以链接到目录、文件或者不存在的文件。删除原始文件或目录不会影响软链接的可用性,但如果软链接指向的目标文件或目录被删除,软链接将失效。
区别总结:
(1)硬链接与原始文件共享相同的索引节点和数据块,而软链接是一个指向目标文件的路径。
(2)硬链接只能链接到同一文件系统中的文件,而软链接可以跨越文件系统边界链接到不同的文件。
(3)删除原始文件不会影响硬链接的可用性,但删除软链接指向的目标文件将使软链接失效。
(4)硬链接不能链接到目录,而软链接可以链接到目录。
1.2. 系统调用和标准库区别?
# 系统调用(System Call)和标准库(Standard Library)是操作系统和编程语言中的两个不同概念。
(1)系统调用:系统调用是操作系统提供给应用程序访问底层核心功能的接口。它们允许应用程序直接与操作系统内核进行交互,请求执行特权操作,如文件操作、进程管理、网络通信等。系统调用提供了一种安全且受控的方式,使应用程序能够利用操作系统的功能。系统调用通常以底层的硬件指令形式存在,应用程序通过调用特定的系统调用号来触发相应的操作系统功能。
(2)标准库:标准库是编程语言提供的一组预定义函数和工具,旨在简化常见任务的实现。标准库通常是由编程语言的开发者或社区提供,并随编程语言的安装包一起提供。标准库提供了丰富的功能,例如字符串处理、数学运算、文件操作、网络通信等。通过使用标准库中的函数和工具,开发人员可以更轻松地实现各种功能,而无需从头开始编写所有必要的代码。
区别总结:
(1)系统调用是操作系统提供的底层接口,用于访问操作系统的核心功能。
(2)标准库是编程语言提供的一组预定义函数和工具,用于简化常见任务的实现。
(3)系统调用允许应用程序直接与操作系统内核交互,请求执行特权操作。
(4)标准库提供了高级抽象和功能,使开发人员能够更轻松地实现各种任务,而无需关注底层细节。
(5)系统调用通常以底层硬件指令形式存在,而标准库是由编程语言的开发者或社区提供的一组函数和工具。
1.3. 假设目前系统的umask为0022,假如编写代码实现creat(“a.txt”, 0765)操作后,请写出文件a.txt的所有者、组用户、其他用户的权限。
# 根据umask值为0022和creat函数的参数0765,我们可以计算出文件a.txt的权限如下:
umask是一个掩码,用于限制新创建文件的默认权限。它通过将文件权限中的对应位设置为0来进行屏蔽。在umask中,第一位表示所有者权限的屏蔽,第二位表示组用户权限的屏蔽,第三位表示其他用户权限的屏蔽。
# 给定的参数是0765,对应的权限为:
所有者权限:7(读、写、执行)
组用户权限:6(读、写)
其他用户权限:5(读、执行)
# umask为0022,对应的权限屏蔽为:
所有者权限屏蔽:2(写)
组用户权限屏蔽:2(写)
其他用户权限屏蔽:2(写)
#进行按位与运算后,得到实际的权限值为:
所有者权限:7 & ~2 = 5(读、执行)
组用户权限:6 & ~2 = 4(读、写)
其他用户权限:5 & ~2 = 5(读、执行)
因此,文件a.txt的权限为:
# txt结果权限:
所有者权限:读、执行(r-x)
组用户权限:读、写(rw-)
其他用户权限:读、执行(r-x)
2. 编程题
2.1. 编写程序实现拷贝文件功能,该程序运行时有两个参数,分别为源文件和目标文件,程序能够显示打开、读取、写入、关闭文件操作时的错误。假定编译后的程序名为mycopy,使用方法如:
./mycopy src.txt dest.txt
(1)编写C语言程序:mycopy.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
FILE *src_file, *dest_file; // 声明源文件和目标文件的指针
char buffer[1024]; // 缓冲区,用于读取和写入数据
size_t nread; // 读取的字节数
if (argc != 3) { // 检查命令行参数个数是否正确
fprintf(stderr, "Usage: %s source_file destination_file\n", argv[0]);
exit(EXIT_FAILURE);
}
src_file = fopen(argv[1], "rb"); // 打开源文件以二进制只读方式
if (src_file == NULL) { // 检查源文件是否成功打开
perror("fopen");
exit(EXIT_FAILURE);
}
dest_file = fopen(argv[2], "wb"); // 打开目标文件以二进制写入方式
if (dest_file == NULL) { // 检查目标文件是否成功打开
perror("fopen");
fclose(src_file);
exit(EXIT_FAILURE);
}
while ((nread = fread(buffer, 1, sizeof(buffer), src_file)) > 0) { // 从源文件读取数据到缓冲区
if (fwrite(buffer, 1, nread, dest_file) != nread) { // 将缓冲区中的数据写入目标文件
perror("fwrite");
fclose(src_file);
fclose(dest_file);
exit(EXIT_FAILURE);
}
}
if (ferror(src_file)) { // 检查在读取源文件时是否发生错误
perror("fread");
fclose(src_file);
fclose(dest_file);
exit(EXIT_FAILURE);
}
if (fclose(src_file) != 0) { // 关闭源文件
perror("fclose");
exit(EXIT_FAILURE);
}
if (fclose(dest_file) != 0) { // 关闭目标文件
perror("fclose");
exit(EXIT_FAILURE);
}
return 0;
}
(2)运用gcc编译器编译程序
gcc -o mycopy mycopy.c
(3)将原文件src.txt,目标文件dest.txt进行输入
./mycopy src.txt dest.txt
2.2. 编写程序实现删除文件功能,该程序运行时有多个参数,可以删除多个参数代表的文件。
- 假定编译后的程序名为myrm,使用方法如下:
./myrm a.txt b.txt c.txt d.txt
- 删除时显示删除信息,删除错误时能够显示删除错误。
(1)编写C语言程序myrm.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int i;
if (argc < 2) { // 检查命令行参数个数是否正确
fprintf(stderr, "Usage: %s file1 file2 file3 ...\n", argv[0]);
exit(EXIT_FAILURE);
}
for (i = 1; i < argc; i++) { // 遍历命令行参数中的文件路径
if (remove(argv[i]) == 0) { // 删除指定的文件
printf("Deleted file: %s\n", argv[i]);
} else {
perror("remove"); // 输出错误信息
exit(EXIT_FAILURE);
}
}
return 0;
}
(2)运用gcc编译器编译程序
gcc -o myrm myrm.c
(3)将需要删除的文件进行路径输入
./myrm a.txt b.txt c.txt d.txt
2.3. 编程要求:
a.txt中内容如下:
Hello World! I am a student of GDUFE! My student NO is 202012345.
编写程序,将内容中的两个student都改为teacher,使用文件指针偏移方法。
(1)编写C语言程序replace.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main() {
FILE *file; // 文件指针
char buffer[BUFFER_SIZE]; // 缓冲区
char *search = "student"; // 要搜索的字符串
char *replace = "teacher"; // 要替换的字符串
long replace_count = 0; // 替换计数器,记录替换的次数
size_t search_len = strlen(search); // 要搜索的字符串长度
size_t replace_len = strlen(replace); // 要替换的字符串长度
file = fopen("a.txt", "r+"); // 以读写方式打开文件
if (file == NULL) { // 检查文件是否成功打开
perror("fopen");
exit(EXIT_FAILURE);
}
while (fgets(buffer, BUFFER_SIZE, file) != NULL) { // 逐行读取文件内容到缓冲区
char *pos = buffer;
while ((pos = strstr(pos, search)) != NULL) { // 在缓冲区中搜索要替换的字符串
fseek(file, pos - buffer, SEEK_CUR); // 定位到要替换的位置
fwrite(replace, 1, replace_len, file); // 将替换字符串写入文件
replace_count++; // 替换计数器加一
pos += search_len; // 继续搜索下一个匹配位置
}
}
if (ferror(file)) { // 检查在读取文件时是否发生错误
perror("fgets");
fclose(file);
exit(EXIT_FAILURE);
}
printf("Replaced %ld occurrences of \"%s\" with \"%s\".\n", replace_count, search, replace); // 输出替换的结果
if (fclose(file) != 0) { // 关闭文件
perror("fclose");
exit(EXIT_FAILURE);
}
return 0;
}
(2)用gcc编译器编译程序
gcc -o replace replace.c
(3)运行程序
./replace
2.4. 编程要求:
- 创建文件file1,写入字符串
abcdefghijklmn
- 创建文件file2,写入字符串
ABCDEFGHIJKLMN
- 读取file1中的内容,写入file2,使file2中的字符串内容为
abcdefghijklmnABCDEFGHIJKLMN
(1)编写C语言程序copy.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// 声明文件指针和缓冲区
FILE *file1, *file2;
char buffer1[100], buffer2[100];
char result[200];
// 打开文件1,如果打开失败则输出错误信息并退出程序
file1 = fopen("file1.txt", "r");
if (file1 == NULL) {
printf("Failed to open file1.txt\n");
return 1;
}
// 打开文件2,如果打开失败则输出错误信息并关闭文件1并退出程序
file2 = fopen("file2.txt", "r");
if (file2 == NULL) {
printf("Failed to open file2.txt\n");
fclose(file1);
return 1;
}
// 从文件1和文件2中读取一行数据到缓冲区中
fgets(buffer1, sizeof(buffer1), file1);
fgets(buffer2, sizeof(buffer2), file2);
// 关闭文件1和文件2
fclose(file1);
fclose(file2);
// 将缓冲区1中的数据复制到结果缓冲区中,并将换行符替换为NULL
strncpy(result, buffer1, strlen(buffer1) - 1);
// 将缓冲区2中的数据追加到结果缓冲区中
strcat(result, buffer2);
// 打开文件2,以写入模式打开,如果打开失败则输出错误信息并退出程序
file2 = fopen("file2.txt", "w");
if (file2 == NULL) {
printf("Failed to open file2.txt\n");
return 1;
}
// 将结果缓冲区中的数据写入文件2中
fputs(result, file2);
// 关闭文件2
fclose(file2);
return 0;
}
(2)用gcc编译器编译程序
gcc -o copy copy.c
(3)运行程序
./copy
2.5. 文件IO编程:补全下面代码,从一个文件(源文件)中读取后10KB数据并复制到另一个文件(目标文件)。
请注意:源文件是以只读方式打开的,目标文件是以只写方式打开(可以是读/写方式)的。若目标文件不存在,可以创建并设置权限的初始值为644,即文件所有者可读可写,文件所属组和其他用户只能读。
(1)编写C语言程序file_copy.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#define BUFFER_SIZE 1024 /* 定义每次读/写缓存大小,影响运行效率 */
#define SRC_FILE_NAME "test-s.txt" /* 定义源文件名 */
#define DEST_FILE_NAME "test-d.txt" /* 定义目标文件名 */
#define OFFSET 10240 /* 定义复制的数据大小 */
int main()
{
int src_file, dest_file;
unsigned char buff[BUFFER_SIZE];
int real_read_len;
/* 打开源文件,以只读方式 */
src_file = open(SRC_FILE_NAME, O_RDONLY);
if(src_file < 0) {
perror("open source file error"); /* 如果打开文件失败,输出错误信息并退出 */
exit(1);
}
/* 打开或创建目标文件,以只写方式,如果文件不存在则创建,权限为644 */
dest_file = open(DEST_FILE_NAME, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if(dest_file < 0) {
perror("open destination file error"); /* 如果打开文件失败,输出错误信息并关闭源文件,然后退出 */
close(src_file);
exit(1);
}
/* 将源文件的读写位置移动到倒数第 OFFSET 个字节的位置 */
if(lseek(src_file, -OFFSET, SEEK_END) < 0) {
perror("lseek error"); /* 如果定位失败,输出错误信息并关闭文件,然后退出 */
close(src_file);
close(dest_file);
exit(1);
}
/* 循环读取源文件的数据并写入目标文件,直到源文件读取完毕 */
while((real_read_len = read(src_file, buff, BUFFER_SIZE)) > 0) {
if(write(dest_file, buff, real_read_len) != real_read_len) {
perror("write error"); /* 如果写入失败,输出错误信息并关闭文件,然后退出 */
close(src_file);
close(dest_file);
exit(1);
}
}
/* 如果读取失败,输出错误信息并关闭文件,然后退出 */
if(real_read_len < 0) {
perror("read error");
close(src_file);
close(dest_file);
exit(1);
}
/* 关闭目标文件和源文件 */
close(dest_file);
close(src_file);
return 0;
}
(2)准备数据文本test-s.txt
(数据量:16.44KB)
{"'d", "'ll", "'m", "'re", "'s", "'t", "'ve", "ZT", "ZZ", "a", "a's", "able", "about", "above", "abst", "accordance", "according", "accordingly", "across", "act", "actually", "added", "adj", "adopted", "affected", "affecting", "affects", "after", "afterwards", "again", "against", "ah", "ain't", "all", "allow", "allows", "almost", "alone", "along", "already", "also", "although", "always", "am", "among", "amongst", "an", "and", "announce", "another", "any", "anybody", "anyhow", "anymore", "anyone", "anything", "anyway", "anyways", "anywhere", "apart", "apparently", "appear", "appreciate", "appropriate", "approximately", "are", "area", "areas", "aren", "aren't", "arent", "arise", "around", "as", "aside", "ask", "asked", "asking", "asks", "associated", "at", "auth", "available", "away", "awfully", "b", "back", "backed", "backing", "backs", "be", "became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "began", "begin", "beginning", "beginnings", "begins", "behind", "being", "beings", "believe", "below", "beside", "besides", "best", "better", "between", "beyond", "big", "biol", "both", "brief", "briefly", "but", "by", "c", "c'mon", "c's", "ca", "came", "can", "can't", "cannot", "cant", "case", "cases", "cause", "causes", "certain", "certainly", "changes", "clear", "clearly", "co", "com", "come", "comes", "concerning", "consequently", "consider", "considering", "contain", "containing", "contains", "corresponding", "could", "couldn't", "couldnt", "course", "currently", "d", "date", "definitely", "describe", "described", "despite", "did", "didn't", "differ", "different", "differently", "discuss", "do", "does", "doesn't", "doing", "don't", "done", "down", "downed", "downing", "downs", "downwards", "due", "during", "e", "each", "early", "ed", "edu", "effect", "eg", "eight", "eighty", "either", "else", "elsewhere", "end", "ended", "ending", "ends", "enough", "entirely", "especially", "et", "et-al", "etc", "even", "evenly", "ever", "every", "everybody", "everyone", "everything", "everywhere", "ex", "exactly", "example", "except", "f", "face", "faces", "fact", "facts", "far", "felt", "few", "ff", "fifth", "find", "finds", "first", "five", "fix", "followed", "following", "follows", "for", "former", "formerly", "forth", "found", "four", "from", "full", "fully", "further", "furthered", "furthering", "furthermore", "furthers", "g", "gave", "general", "generally", "get", "gets", "getting", "give", "given", "gives", "giving", "go", "goes", "going", "gone", "good", "goods", "got", "gotten", "great", "greater", "greatest", "greetings", "group", "grouped", "grouping", "groups", "h", "had", "hadn't", "happens", "hardly", "has", "hasn't", "have", "haven't", "having", "he", "he's", "hed", "hello", "help", "hence", "her", "here", "here's", "hereafter", "hereby", "herein", "heres", "hereupon", "hers", "herself", "hes", "hi", "hid", "high", "higher", "highest", "him", "himself", "his", "hither", "home", "hopefully", "how", "howbeit", "however", "hundred", "i", "i'd", "i'll", "i'm", "i've", "id", "ie", "if", "ignored", "im", "immediate", "immediately", "importance", "important", "in", "inasmuch", "inc", "include", "indeed", "index", "indicate", "indicated", "indicates", "information", "inner", "insofar", "instead", "interest", "interested", "interesting", "interests", "into", "invention", "inward", "is", "isn't", "it", "it'd", "it'll", "it's", "itd", "its", "itself", "j", "just", "k", "keep", "keeps", "kept", "keys", "kg", "kind", "km", "knew", "know", "known", "knows", "l", "large", "largely", "last", "lately", "later", "latest", "latter", "latterly", "least", "less", "lest", "let", "let's", "lets", "like", "liked", "likely", "line", "little", "long", "longer", "longest", "look", "looking", "looks", "ltd", "m", "made", "mainly", "make", "makes", "making", "man", "many", "may", "maybe", "me", "mean", "means", "meantime", "meanwhile", "member", "members", "men", "merely", "mg", "might", "million", "miss", "ml", "more", "moreover", "most", "mostly", "mr", "mrs", "much", "mug", "must", "my", "myself", "n", "n't", "na", "name", "namely", "nay", "nd", "near", "nearly", "necessarily", "necessary", "need", "needed", "needing", "needs", "neither", "never", "nevertheless", "new", "newer", "newest", "next", "nine", "ninety", "no", "nobody", "non", "none", "nonetheless", "noone", "nor", "normally", "nos", "not", "noted", "nothing", "novel", "now", "nowhere", "number", "numbers", "o", "obtain", "obtained", "obviously", "of", "off", "often", "oh", "ok", "okay", "old", "older", "oldest", "omitted", "on", "once", "one", "ones", "only", "onto", "open", "opened", "opening", "opens", "or", "ord", "order", "ordered", "ordering", "orders", "other", "others", "otherwise", "ought", "our", "ours", "ourselves", "out", "outside", "over", "overall", "owing", "own", "p", "page", "pages", "part", "parted", "particular", "particularly", "parting", "parts", "past", "per", "perhaps", "place", "placed", "places", "please", "plus", "point", "pointed", "pointing", "points", "poorly", "possible", "possibly", "potentially", "pp", "predominantly", "present", "presented", "presenting", "presents", "presumably", "previously", "primarily", "probably", "problem", "problems", "promptly", "proud", "provides", "put", "puts", "q", "que", "quickly", "quite", "qv", "r", "ran", "rather", "rd", "re", "readily", "really", "reasonably", "recent", "recently", "ref", "refs", "regarding", "regardless", "regards", "related", "relatively", "research", "respectively", "resulted", "resulting", "results", "right", "room", "rooms", "run", "s", "said", "same", "saw", "say", "saying", "says", "sec", "second", "secondly", "seconds", "section", "see", "seeing", "seem", "seemed", "seeming", "seems", "seen", "sees", "self", "selves", "sensible", "sent", "serious", "seriously", "seven", "several", "shall", "she", "she'll", "shed", "shes", "should", "shouldn't", "show", "showed", "showing", "shown", "showns", "shows", "side", "sides", "significant", "significantly", "similar", "similarly", "since", "six", "slightly", "small", "smaller", "smallest", "so", "some", "somebody", "somehow", "someone", "somethan", "something", "sometime", "sometimes", "somewhat", "somewhere", "soon", "sorry", "specifically", "specified", "specify", "specifying", "state", "states", "still", "stop", "strongly", "sub", "substantially", "successfully", "such", "sufficiently", "suggest", "sup", "sure", "t", "t's", "take", "taken", "taking", "tell", "tends", "th", "than", "thank", "thanks", "thanx", "that", "that'll", "that's", "that've", "thats", "the", "their", "theirs", "them", "themselves", "then", "thence", "there", "there'll", "there's", "there've", "thereafter", "thereby", "thered", "therefore", "therein", "thereof", "therere", "theres", "thereto", "thereupon", "these", "they", "they'd", "they'll", "they're", "they've", "theyd", "theyre", "thing", "things", "think", "thinks", "third", "this", "thorough", "thoroughly", "those", "thou", "though", "thoughh", "thought", "thoughts", "thousand", "three", "throug", "through", "throughout", "thru", "thus", "til", "tip", "to", "today", "together", "too", "took", "toward", "towards", "tried", "tries", "truly", "try", "trying", "ts", "turn", "turned", "turning", "turns", "twice", "two", "u", "un", "under", "unfortunately", "unless", "unlike", "unlikely", "until", "unto", "up", "upon", "ups", "us", "use", "used", "useful", "usefully", "usefulness", "uses", "using", "usually", "uucp", "v", "value", "various", "very", "via", "viz", "vol", "vols", "vs", "w", "want", "wanted", "wanting", "wants", "was", "wasn't", "way", "ways", "we", "we'd", "we'll", "we're", "we've", "wed", "welcome", "well", "wells", "went", "were", "weren't", "what", "what'll", "what's", "whatever", "whats", "when", "whence", "whenever", "where", "where's", "whereafter", "whereas", "whereby", "wherein", "wheres", "whereupon", "wherever", "whether", "which", "while", "whim", "whither", "who", "who'll", "who's", "whod", "whoever", "whole", "whom", "whomever", "whos", "whose", "why", "widely", "will", "willing", "wish", "with", "within", "without", "won't", "wonder", "words", "work", "worked", "working", "works", "world", "would", "wouldn't", "www", "x", "y", "year", "years", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "youd", "young", "younger", "youngest", "your", "youre", "yours", "yourself", "yourselves", "z", "zero", "zt", "zz"}
{"'d", "'ll", "'m", "'re", "'s", "'t", "'ve", "ZT", "ZZ", "a", "a's", "able", "about", "above", "abst", "accordance", "according", "accordingly", "across", "act", "actually", "added", "adj", "adopted", "affected", "affecting", "affects", "after", "afterwards", "again", "against", "ah", "ain't", "all", "allow", "allows", "almost", "alone", "along", "already", "also", "although", "always", "am", "among", "amongst", "an", "and", "announce", "another", "any", "anybody", "anyhow", "anymore", "anyone", "anything", "anyway", "anyways", "anywhere", "apart", "apparently", "appear", "appreciate", "appropriate", "approximately", "are", "area", "areas", "aren", "aren't", "arent", "arise", "around", "as", "aside", "ask", "asked", "asking", "asks", "associated", "at", "auth", "available", "away", "awfully", "b", "back", "backed", "backing", "backs", "be", "became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "began", "begin", "beginning", "beginnings", "begins", "behind", "being", "beings", "believe", "below", "beside", "besides", "best", "better", "between", "beyond", "big", "biol", "both", "brief", "briefly", "but", "by", "c", "c'mon", "c's", "ca", "came", "can", "can't", "cannot", "cant", "case", "cases", "cause", "causes", "certain", "certainly", "changes", "clear", "clearly", "co", "com", "come", "comes", "concerning", "consequently", "consider", "considering", "contain", "containing", "contains", "corresponding", "could", "couldn't", "couldnt", "course", "currently", "d", "date", "definitely", "describe", "described", "despite", "did", "didn't", "differ", "different", "differently", "discuss", "do", "does", "doesn't", "doing", "don't", "done", "down", "downed", "downing", "downs", "downwards", "due", "during", "e", "each", "early", "ed", "edu", "effect", "eg", "eight", "eighty", "either", "else", "elsewhere", "end", "ended", "ending", "ends", "enough", "entirely", "especially", "et", "et-al", "etc", "even", "evenly", "ever", "every", "everybody", "everyone", "everything", "everywhere", "ex", "exactly", "example", "except", "f", "face", "faces", "fact", "facts", "far", "felt", "few", "ff", "fifth", "find", "finds", "first", "five", "fix", "followed", "following", "follows", "for", "former", "formerly", "forth", "found", "four", "from", "full", "fully", "further", "furthered", "furthering", "furthermore", "furthers", "g", "gave", "general", "generally", "get", "gets", "getting", "give", "given", "gives", "giving", "go", "goes", "going", "gone", "good", "goods", "got", "gotten", "great", "greater", "greatest", "greetings", "group", "grouped", "grouping", "groups", "h", "had", "hadn't", "happens", "hardly", "has", "hasn't", "have", "haven't", "having", "he", "he's", "hed", "hello", "help", "hence", "her", "here", "here's", "hereafter", "hereby", "herein", "heres", "hereupon", "hers", "herself", "hes", "hi", "hid", "high", "higher", "highest", "him", "himself", "his", "hither", "home", "hopefully", "how", "howbeit", "however", "hundred", "i", "i'd", "i'll", "i'm", "i've", "id", "ie", "if", "ignored", "im", "immediate", "immediately", "importance", "important", "in", "inasmuch", "inc", "include", "indeed", "index", "indicate", "indicated", "indicates", "information", "inner", "insofar", "instead", "interest", "interested", "interesting", "interests", "into", "invention", "inward", "is", "isn't", "it", "it'd", "it'll", "it's", "itd", "its", "itself", "j", "just", "k", "keep", "keeps", "kept", "keys", "kg", "kind", "km", "knew", "know", "known", "knows", "l", "large", "largely", "last", "lately", "later", "latest", "latter", "latterly", "least", "less", "lest", "let", "let's", "lets", "like", "liked", "likely", "line", "little", "long", "longer", "longest", "look", "looking", "looks", "ltd", "m", "made", "mainly", "make", "makes", "making", "man", "many", "may", "maybe", "me", "mean", "means", "meantime", "meanwhile", "member", "members", "men", "merely", "mg", "might", "million", "miss", "ml", "more", "moreover", "most", "mostly", "mr", "mrs", "much", "mug", "must", "my", "myself", "n", "n't", "na", "name", "namely", "nay", "nd", "near", "nearly", "necessarily", "necessary", "need", "needed", "needing", "needs", "neither", "never", "nevertheless", "new", "newer", "newest", "next", "nine", "ninety", "no", "nobody", "non", "none", "nonetheless", "noone", "nor", "normally", "nos", "not", "noted", "nothing", "novel", "now", "nowhere", "number", "numbers", "o", "obtain", "obtained", "obviously", "of", "off", "often", "oh", "ok", "okay", "old", "older", "oldest", "omitted", "on", "once", "one", "ones", "only", "onto", "open", "opened", "opening", "opens", "or", "ord", "order", "ordered", "ordering", "orders", "other", "others", "otherwise", "ought", "our", "ours", "ourselves", "out", "outside", "over", "overall", "owing", "own", "p", "page", "pages", "part", "parted", "particular", "particularly", "parting", "parts", "past", "per", "perhaps", "place", "placed", "places", "please", "plus", "point", "pointed", "pointing", "points", "poorly", "possible", "possibly", "potentially", "pp", "predominantly", "present", "presented", "presenting", "presents", "presumably", "previously", "primarily", "probably", "problem", "problems", "promptly", "proud", "provides", "put", "puts", "q", "que", "quickly", "quite", "qv", "r", "ran", "rather", "rd", "re", "readily", "really", "reasonably", "recent", "recently", "ref", "refs", "regarding", "regardless", "regards", "related", "relatively", "research", "respectively", "resulted", "resulting", "results", "right", "room", "rooms", "run", "s", "said", "same", "saw", "say", "saying", "says", "sec", "second", "secondly", "seconds", "section", "see", "seeing", "seem", "seemed", "seeming", "seems", "seen", "sees", "self", "selves", "sensible", "sent", "serious", "seriously", "seven", "several", "shall", "she", "she'll", "shed", "shes", "should", "shouldn't", "show", "showed", "showing", "shown", "showns", "shows", "side", "sides", "significant", "significantly", "similar", "similarly", "since", "six", "slightly", "small", "smaller", "smallest", "so", "some", "somebody", "somehow", "someone", "somethan", "something", "sometime", "sometimes", "somewhat", "somewhere", "soon", "sorry", "specifically", "specified", "specify", "specifying", "state", "states", "still", "stop", "strongly", "sub", "substantially", "successfully", "such", "sufficiently", "suggest", "sup", "sure", "t", "t's", "take", "taken", "taking", "tell", "tends", "th", "than", "thank", "thanks", "thanx", "that", "that'll", "that's", "that've", "thats", "the", "their", "theirs", "them", "themselves", "then", "thence", "there", "there'll", "there's", "there've", "thereafter", "thereby", "thered", "therefore", "therein", "thereof", "therere", "theres", "thereto", "thereupon", "these", "they", "they'd", "they'll", "they're", "they've", "theyd", "theyre", "thing", "things", "think", "thinks", "third", "this", "thorough", "thoroughly", "those", "thou", "though", "thoughh", "thought", "thoughts", "thousand", "three", "throug", "through", "throughout", "thru", "thus", "til", "tip", "to", "today", "together", "too", "took", "toward", "towards", "tried", "tries", "truly", "try", "trying", "ts", "turn", "turned", "turning", "turns", "twice", "two", "u", "un", "under", "unfortunately", "unless", "unlike", "unlikely", "until", "unto", "up", "upon", "ups", "us", "use", "used", "useful", "usefully", "usefulness", "uses", "using", "usually", "uucp", "v", "value", "various", "very", "via", "viz", "vol", "vols", "vs", "w", "want", "wanted", "wanting", "wants", "was", "wasn't", "way", "ways", "we", "we'd", "we'll", "we're", "we've", "wed", "welcome", "well", "wells", "went", "were", "weren't", "what", "what'll", "what's", "whatever", "whats", "when", "whence", "whenever", "where", "where's", "whereafter", "whereas", "whereby", "wherein", "wheres", "whereupon", "wherever", "whether", "which", "while", "whim", "whither", "who", "who'll", "who's", "whod", "whoever", "whole", "whom", "whomever", "whos", "whose", "why", "widely", "will", "willing", "wish", "with", "within", "without", "won't", "wonder", "words", "work", "worked", "working", "works", "world", "would", "wouldn't", "www", "x", "y", "year", "years", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "youd", "young", "younger", "youngest", "your", "youre", "yours", "yourself", "yourselves", "z", "zero", "zt", "zz"}
(3)运用gcc编译器进行编译
gcc -o file_copy file_copy.c
(4)运行程序
./file_copy
2.6. 创建新文件aa.txt,内容“Hello World!”,该文件具有用户读写权限。采用fcntl 复制一个新的文件描述符,通过新文件描述符向文件末尾写入“Linux is an open source OS.”字符串。
(1)编写C语言程序file_fcntl.c
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#define FILE_NAME "aa.txt" /* 文件名 */
#define ADD_STR "Linux is an open source OS." /* 要添加的字符串 */
int main() {
int fd, new_fd;
ssize_t write_len;
/* 打开文件 */
fd = open(FILE_NAME, O_RDWR);
if(fd < 0) {
perror("open file error");
return 1;
}
/* 使用 fcntl 复制文件描述符 */
new_fd = fcntl(fd, F_DUPFD, 0);
if(new_fd < 0) {
perror("fcntl error");
close(fd);
return 1;
}
/* 将新文件描述符的读写位置移动到文件末尾 */
if(lseek(new_fd, 0, SEEK_END) < 0) {
perror("lseek error");
close(fd);
close(new_fd);
return 1;
}
/* 通过新文件描述符向文件末尾写入字符串 */
write_len = write(new_fd, ADD_STR, strlen(ADD_STR));
if(write_len != strlen(ADD_STR)) {
perror("write error");
close(fd);
close(new_fd);
return 1;
}
/* 关闭文件描述符 */
close(new_fd);
close(fd);
return 0;
}
(2)运用gcc编译器进行程序编译
gcc -o file_fcntl file_fcntl.c
(3)运行程序
./file_fcntl
2.7. 编写程序,对未知txt文件word.txt中所有的is修改成are。如果存在is,就进行修改;如果不存在is,就不做修改。
注意:word.txt文件由自己编写测试。
选做
(1)编写C语言程序word_replace.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SRC_FILE_NAME "word.txt"
#define TEMP_FILE_NAME "temp.txt"
#define FIND "is"
#define REPLACE "are"
int main() {
FILE *src_file, *temp_file;
char *line = NULL, *pos;
size_t len = 0;
ssize_t read_len;
/* 打开源文件和临时文件 */
src_file = fopen(SRC_FILE_NAME, "r");
temp_file = fopen(TEMP_FILE_NAME, "w");
if(src_file == NULL || temp_file == NULL) {
perror("open file error");
return 1;
}
/* 逐行读取源文件 */
while((read_len = getline(&line, &len, src_file)) != -1) {
char *temp = line;
/* 在每一行中查找并替换字符串 */
while((pos = strstr(temp, FIND)) != NULL) {
/* 将查找到的字符串之前的内容写入临时文件 */
fwrite(temp, sizeof(char), pos - temp, temp_file);
/* 将替换字符串写入临时文件 */
fwrite(REPLACE, sizeof(char), strlen(REPLACE), temp_file);
/* 移动行缓冲区的指针 */
temp = pos + strlen(FIND);
}
/* 将剩余的内容写入临时文件 */
fputs(temp, temp_file);
}
/* 关闭文件和释放内存 */
free(line);
fclose(src_file);
fclose(temp_file);
/* 删除源文件并将临时文件重命名为源文件 */
remove(SRC_FILE_NAME);
rename(TEMP_FILE_NAME, SRC_FILE_NAME);
return 0;
}
(2)编写word.txt文件
He is a very excellent teacher! His favorite book is about Linux!
(3)用gcc编译器进行程序编译
gcc -o word_replace word_replace.c
(4)运行程序
./word_replace
2.8. 存在两个txt文件,分别为a.txt与b.txt,a.txt内容为“Captain: Are ya ready kids?” ,b.txt中的内容是“Kids: Aye Aye Captain.”。将a.txt中的内容复制到b.txt中,把b.txt中的内容复制到a.txt中。
选做
(1)编写C语言程序copy_file.c
#include <stdio.h>
#include <stdlib.h>
#define FILE_A "a.txt"
#define FILE_B "b.txt"
#define TEMP_FILE "temp.txt"
void copy_file(const char *src_file, const char *dst_file) {
FILE *src, *dst;
char ch;
src = fopen(src_file, "r");
dst = fopen(dst_file, "w");
if(src == NULL || dst == NULL) {
perror("Error in opening file");
exit(EXIT_FAILURE);
}
while((ch = fgetc(src)) != EOF) {
fputc(ch, dst);
}
fclose(src);
fclose(dst);
}
int main() {
/* 将 a.txt 的内容复制到临时文件 */
copy_file(FILE_A, TEMP_FILE);
/* 将 b.txt 的内容复制到 a.txt */
copy_file(FILE_B, FILE_A);
/* 将临时文件的内容复制到 b.txt */
copy_file(TEMP_FILE, FILE_B);
/* 删除临时文件 */
remove(TEMP_FILE);
return 0;
}
(2)用gcc编译器进行程序编译
gcc -o copy_file copy_file.c
(3)运行程序
./copy_file