文件处理与随机抽样实现
任务一:文本行数与有效字符统计
通过读取指定路径的文本文件,统计其总行数及非空白字符数量。程序使用 fgetc逐字符读取文件内容,并在遍历过程中累计换行符以计算行数,同时忽略空格、制表符和换行符,仅计数实际有效字符。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* file_handle;
int line_count = 0;
int char_count = 0;
char current_char;
file_handle = fopen("C:\\Users\\空白\\Desktop\\C语言\\实验7数据文件及部分代码_gbk\\data4.txt", "r");
if (!file_handle) {
perror("文件打开失败");
return 1;
}
while ((current_char = fgetc(file_handle)) != EOF) {
if (current_char == '\n') {
line_count++;
}
if (current_char != ' ' && current_char != '\t' && current_char != '\n') {
char_count++;
}
}
if (char_count > 0 && current_char != '\n') {
line_count++;
}
printf("data4.txt统计结果\n");
printf("行数: %d\n", line_count);
printf("有效字符数: %d\n", char_count);
fclose(file_handle);
return 0;
}
任务二:从名单中随机抽取五条记录
程序读取一个包含多条记录的原始列表文件,将每行存入二维字符数组,随后利用随机数生成器从所有记录中无重复地选取五条,并写入用户指定的新文件中。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_LINES 100
#define LINE_LENGTH 100
int main() {
char records[MAX_LINES][LINE_LENGTH];
FILE* input_file;
FILE* output_file;
char output_filename[80];
int record_count = 0;
int selected_indices[MAX_LINES] = {0};
int i, random_index, selected = 0;
gets(output_filename);
input_file = fopen("C:\\Users\\空白\\Desktop\\C语言\\实验7数据文件及部分代码_gbk\\list.txt", "r");
output_file = fopen(output_filename, "w");
if (!input_file) {
perror("输入文件打开失败");
return 1;
}
if (!output_file) {
perror("输出文件创建失败");
return 2;
}
while (fgets(records[record_count], LINE_LENGTH, input_file) != NULL) {
record_count++;
}
srand(time(NULL));
while (selected < 5) {
random_index = rand() % record_count;
if (selected_indices[random_index] == 0) {
printf("%s", records[random_index]);
fprintf(output_file, "%s", records[random_index]);
selected_indices[random_index] = 1;
selected++;
}
}
fclose(input_file);
fclose(output_file);
return 0;
}