一. 思维导图
二. 练习
1) 获取系统时间,并将系统时间写入文件中。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define TIME_FILE_PATH "./time.txt"
//获取当前时间字符串
void fetchCurrentTime(char timeStr[]) {
time_t t;
time(&t);
struct tm *timeFormat = localtime(&t);
sprintf(timeStr, "%4d-%02d-%02d %02d:%02d:%02d",
timeFormat->tm_year+1900,
timeFormat->tm_mon+1,
timeFormat->tm_mday,
timeFormat->tm_hour,
timeFormat->tm_min,
timeFormat->tm_sec);
}
//获取文件的行数
int fetchFileLine() {
FILE *fp;
if ((fp = fopen(TIME_FILE_PATH, "r")) == NULL) {
perror("open file");
return -1;
}
char buf[10];
int count = 0;
while(fgets(buf, sizeof(buf), fp) != NULL) {
if(buf[strlen(buf)-1] == '\n') {
count++;
}
}
fclose(fp);
return count;
}
//剥离每一行的时间string, 去除"1)", "2)"等前缀
void filterPureTime(char str[]) {
int index = 0;
while(str[index] != ')') {
index++;
}
if (index > 0) {
int i=0;
for (i=0; i<strlen(str); i++) {
str[i] = str[i+index+1];
}
str[i] = '\0';
}
}
//判断当前时间,是否在文件中出现过 出现过,返回1, 没出现过,返回0
int findTimeInFile(const char curTime[]) {
FILE *fp;
if ((fp = fopen(TIME_FILE_PATH, "r")) == NULL) {
perror("file open");
return -1;
}
char buf[200];
char buf2[200];
while((fscanf(fp, "%s %s", buf, buf2)) != EOF) {
char orgStr[100];
sprintf(orgStr, "%s %s", buf, buf2);
char pureTime[100];
strcpy(pureTime, orgStr);
filterPureTime(pureTime);
if (strcmp(pureTime, curTime) == 0) {
fclose(fp);
return 1;
}
}
fclose(fp);
return 0;
}
//向文件输出带序列号的时间字符串
void outputTime() {
FILE *fp;
if ((fp = fopen(TIME_FILE_PATH, "a")) == NULL) {
perror("file open");
return;
}
//获取原有文件行数,新输入的序列号以原有行数为基础增加。
int count = fetchFileLine()+1;
count = count == 0 ? 1 : count;
while(1) {
char timeStr[20];
fetchCurrentTime(timeStr);
char toWStr[50];
//当当前时间没有在原文件中出现过时,进行增加
if (findTimeInFile(timeStr) == 0) {
sprintf(toWStr, "%d)%s\n", count, timeStr);
fprintf(fp, "%s", toWStr);
count++;
fflush(fp);
}
}
}
int main(int argc, const char *argv[]) {
outputTime();
return 0;
}
结果展示:
2) 使用fread和fwrite完成两个文件的拷贝
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void copyFile(const char *destFile, const char *srcFile) {
FILE *destfp, *srcfp;
if ((destfp = fopen(destFile, "w")) == NULL) {
perror("dest file open");
return;
}
if ((srcfp = fopen(srcFile, "r")) == NULL) {
perror("src file open");
return;
}
char buf[50];
while(1) {
int freadStatus = fread(buf, sizeof(buf), 1, srcfp);
fwrite(buf, 1, sizeof(buf)-1, destfp);
if (feof(srcfp)) {
break;
}
}
fclose(destfp);
fclose(srcfp);
}
int main(int argc, const char *argv[]) {
copyFile("./2_test.txt", "./2.c");
return 0;
}