c - 查找输入文件中的最大行长和最大行数,但出现段错误?
问题描述
我正在尝试将文件输入到二维数组中,但是在尝试查找最大行长和最大行数时出现段错误。seg 错误发生在函数 checkSpelling 中。我尝试使用 gdb 查看 seg 错误发生的位置,但我得到它立即退出,我不完全理解。我的代码如下。任何帮助是极大的赞赏。
#define MAX 1000000
struct TData{
char **pChar;
};
int checkSpelling(const char *input, const char *dict, struct TData *pInput, struct TData *pDictionary);
int searchReplace(const char *input, const char *dict, struct TData *pInput, struct TData *pDictionary);
int save(const char *input, const char *output);
int main (int argc, char **argv){
struct TData input, dictionary, output;
int choice = 0;
if(argc != 4){
printf("Not enough input arguments in the command line.\n");
exit(1);
}
do{
printf("Menu\n");
printf("1. Check the spelling for the file using the dictionary.\n");
printf("2. Search and replace a given string in the inputed file.\n");
printf("3. Save the modified file to the output file.\n");
printf("4. Exit the program.\n");
scanf("%d", &choice);
switch(choice){
case 1:
checkSpelling(argv[1], argv[3], &input, &dictionary);
break;
case 2:
searchReplace(argv[1], argv[3], &input, &dictionary);
break;
case 3:
save(argv[1],argv[2]);
break;
case 4:
choice = 4;
break;
default:
printf("Input is invalid");
break;
}
}while (choice != 4);
return 0;
}
int checkSpelling(const char *input, const char *dicto, struct TData *pInput, struct TData *pDictionary){
FILE *inputFile;
FILE *dictFile;
int i = 0, j = 0, k = 0, l = 0, m = 0;
char temp[60], dicttemp[60];
int rowCount = 0, charCount = 0;
printf("Checking the spelling of the inputed file.\n");
printf("Opening the inputed file...\n");
if((inputFile = fopen(input, "rt")) == NULL){
printf("Cannot open file\n");
exit(1);
}
printf("Opening the dictonary...\n");
if((dictFile = fopen(dicto, "rt")) == NULL){
printf("Cannot open dictionary\n");
exit(1);
}
while(!feof(inputFile)){
if(pInput->pChar[i][j] == '\n'){
rowCount++;
}
}
rewind(inputFile);
pInput->pChar[i][j] = 0;
while(pInput->pChar[i][j] != '\n'){
charCount++;
}
rewind(inputFile);
printf("Lines: %d, Max line length: %d", rowCount, charCount);
fclose(inputFile);
fclose(dictFile);
printf("\n");
return 0;
}
解决方案
这是一个示例任务的小代码
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 1000
int main()
{
FILE *fp;
char line[MAX_LENGTH];
size_t n_rows, n_cols, length;
fp = fopen("myfile.txt", "r");
n_cols = 0;
n_rows = 0;
while (fgets(line, MAX_LENGTH, fp) != NULL) {
n_rows++;
length = strlen(line);
if (length > n_cols)
n_cols = length;
}
fclose(fp);
/* the number of lines is in n_rows and the max line length is in n_cols
do whatever you want with them */
return 0;
}
推荐阅读
- javascript - 有没有人知道pdfgeneratorapi.com的诀窍,我正在尝试通过服务器链接从api数据生成PDF,但不断出错
- stata - 以公斤和克为单位的一个变量。另一个表示哪个单位;我怎样才能得到以公斤为单位的新变量?
- r - 如何从具有相同前缀的.y中减去多个.x
- r - broom::tidy 在多项回归中失败
- python - 提取每列的值并将每个索引值存储在列表/字典中
- python - 如何在 SQLAlchemy 中获得类似 .issubset() 的东西?
- filter - 使用 FFT 的一阶差分滤波器的传递函数
- mysql - MySQL - 合并来自两个表的数据(它们位于不同的服务器上)
- r - R闪亮用消息替换空图
- java - 难以对用户输入的 10 个数字进行排序。必须使用数组和单独的排序方法