问题遇到的现象和发生背景
尝试写一个在Linux(redhat)环境下写一个读取文件中指定一行的程序,但不论怎么改都报这个错误
遇到的现象和发生背景,请写出第一个错误信息
Program received signal SIGSEGV, Segmentation fault.
用代码块功能插入代码,请勿粘贴截图。 不用代码块回答率下降 50%
LinesEquals20.txt文件内容如下:
1
……
20
共20行,每行一个数字。
#include <cstdio>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <vector>
#define null NULL
#define Null NULL
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_CHAR0 = 'q',
QUIT_CHAR1 = 'Q'
}quit_char;
const int MAX_LINE_SIZE = 1024; //单个文件最大行数
const int MAX_STRING_SIZE = 256; //单个字符串最大长度
void readLine(FILE* file_opened_ptr, int num) //读取单行内容的函数
{
if (num > 0 && num < MAX_LINE_SIZE)
{
char* tempFileStr = null;
char* tempStr[MAX_LINE_SIZE] = {};
fscanf(file_opened_ptr, "%s", tempFileStr);
char** saveChar = nullptr;
for (ushort i = 0; i < num; i++)
{
tempStr[i] = strtok_r(tempFileStr, "\n", saveChar);
}
printf("Line %d:\n%s", num, tempStr[num]);
}
else
{
printf("File overflow! Line code must between 1 to %d", MAX_LINE_SIZE);
}
}
void fileReadInLines() //读取指定行
{
FILE* file_ptr = null;
char file_name[MAX_STRING_SIZE] = {}, temp;
printf("Please input your file name here:\n");
scanf("%s", &file_name);
getchar(); //消去行尾回车换行符
printf("Please enter your file type with *One Character Only*.\nT[ext]|B[inary]\nInput:\n");
temp = getchar();
int num = 0;
printf("Plese put your line code here:\n");
scanf("%d", &num);
if ((temp == TEXT_CHAR_TOKEN0) || (temp == TEXT_CHAR_TOKEN1))
{
file_ptr = fopen(file_name, "r");
if (file_ptr == null)
{
printf("File not exist.");
}
else
{
readLine(file_ptr, num);
fclose(file_ptr);
}
}
else if ((temp == BINARY_CHAR_TOKEN0) || (temp == BINARY_CHAR_TOKEN1))
{
file_ptr = fopen(file_name, "rb");
if (file_ptr == null)
{
printf("File not exist.");
}
else
{
readLine(file_ptr, num);
fclose(file_ptr);
}
}
}
int main()
{
//fileOperate();
fileReadInLines();
return 0;
}
运行结果及详细报错内容
(gdb) run a.out
Starting program: /home/fredhuang/a.out a.out
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".
Please input your file name here:
LinesEquals20.txt
Please enter your file type with *One Character Only*.
T[ext]|B[inary]
Input:
t
Plese put your line code here:
3
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b3fb40 in strtok_r () from /lib64/libc.so.6
Missing separate debuginfos, use: dnf debuginfo-install glibc-2.34-40.el9_1.1.x86_64 libgcc-11.3.1-2.1.el9.x86_64 libstdc++-11.3.1-2.1.el9.x86_64
我的解答思路和尝试过的方法,不写自己思路的,回答率下降 60%
我尝试过getline方法和ifstream方法,都是一样的报错