>>No.55391831
//#define _CRT_SECURE_NO_WARNINGS
#include "LineReader.h"
#include <cstdio>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
using namespace std;
enum EndOfLineCharEnum //行尾字符枚举
{
CR = '\r', //回车
LF = '\n' //换行
}end_of_line;
enum TextFileCharTokenEnum //表示文本类型的字符
{
TEXT_CHAR_TOKEN0 = 't',
TEXT_CHAR_TOKEN1 = 'T'
}text_char_token;
enum BinaryFileCharTokenEnum //表示二进制类型的字符
{
BINARY_CHAR_TOKEN0 = 'b',
BINARY_CHAR_TOKEN1 = 'B'
}binary_char_token;
enum QuitCharEnum //退出字符枚举,暂时用不到?
{
QUIT_CHAR_TOKEN0 = 'q',
QUIT_CHAR_TOKEN1 = 'Q'
}quit_char_token;
const int MAX_LINE_SIZE = 1024; //单个文件最大行数
const int MAX_STRING_SIZE = 256; //单个字符串最大长度
void readLine(FILE* file_opened_ptr, int num) //读取单行内容的函数
{
int unuse_int_value = 0;
char unuse_char_value = 0;
if (num > 0 && num < MAX_LINE_SIZE)
{
char tempFileStr[MAX_LINE_SIZE] = {};
char* tempStr[MAX_LINE_SIZE] = {};
fscanf_s(file_opened_ptr, "%s", &tempFileStr, MAX_LINE_SIZE);
char* saveChar = nullptr;
char* p = strtok_s(tempFileStr, "\n", &saveChar); //strtok初始化
tempStr0[0,0] = p; //保存第一行
for (int i = 0; i < num - 1; i++) //第一行已经保存,从1开始
{
p = strtok_s(NULL, "\n", &saveChar); //再次使用strtok函数需要将字符值设置为NULL来输出后续字符串
tempStr[i + 1] = p; //获取后续字符串
printf(tempStr[i + 1]);
}
printf("Line %d:\n%s\n", num, tempStr[num - 1]);
}
else
{
printf("File overflow! Line code must between 1 to %d\n", MAX_LINE_SIZE);
}
}
void fileReadInLines() //读取指定行
{
FILE* file_ptr = NULL;
char file_name[MAX_STRING_SIZE] = {}, temp = '\0';
int unuse_int_value = 0;
char unuse_char_value = 0;
printf("Please input your file name here:\n");
unuse_int_value = scanf_s("%s", &file_name, MAX_LINE_SIZE);
unuse_char_value = getchar(); //消去行尾回车换行符
printf("Please enter your file type with *One Character Only*.\nT[ext]|B[inary]\nInput:\n");
temp = getchar();
int num = 0;
if ((temp == TEXT_CHAR_TOKEN0) || (temp == TEXT_CHAR_TOKEN1))
{
printf("Plese put your line code here:\n");
unuse_int_value = scanf_s("%d", &num);
unuse_char_value = getchar(); //消去行尾回车换行符
fopen_s(&file_ptr, file_name, "r");
if (file_ptr == NULL)
{
printf("File not exist.\n");
unuse_char_value = getchar(); //暂停并等待
}
else
{
readLine(file_ptr, num);
unuse_char_value = getchar(); //暂停并等待
fclose(file_ptr);
}
}
else if ((temp == BINARY_CHAR_TOKEN0) || (temp == BINARY_CHAR_TOKEN1))
{
printf("Plese put your line code here:\n");
unuse_int_value = scanf_s("%d", &num);
unuse_char_value = getchar(); //消去行尾回车换行符
fopen_s(&file_ptr, file_name, "rb");
if (file_ptr == NULL)
{
printf("File not exist.\n");
unuse_char_value = getchar(); //暂停并等待
}
else
{
readLine(file_ptr, num);
unuse_char_value = getchar(); //暂停并等待
fclose(file_ptr);
}
}
else
{
printf("Wrong input.");
unuse_char_value = getchar(); //暂停并等待
}
}