c语言读入txt多维数据库,将句子从txt文件解析为C语言中的多维数组

这真让我抓狂。 我正在尝试从txt文件中解析每个句子(即点之间的所有字符),并将每个句子插入数组。 最终目标是拥有一个多维数组,每个句子作为单个数组。

我设法到达了我认为应该可以工作的地步,但是我从行numOfRow++收到分段错误(核心转储)错误

void parseRows(FILE* file){

int c;

int numOfRow = 0;

int numOfChar = 0;

int numOfRows = countNumOfRows(file);

fseek(file, 0, SEEK_SET); // Reset file pointer position to the beginning

char **rows = malloc(numOfRows*sizeof(char*));

for (int i=0; i < numOfRows; i++) rows[i] = malloc(1000*sizeof(char));

while ((c=fgetc(file))!= EOF) {

if (c != '.') {

rows[numOfRow][numOfChar] = c;

numOfChar++;

} else {

rows[numOfRow][numOfChar] = '\0';

numOfRow++;       // This is throwing the error

numOfChar = 0;

}

}

printOutput(rows, numOfRows);

}

如果我注释掉该行,程序将覆盖第一个数组的每一行,并且我只得到最后一句话,因此我知道它正在工作。

我想念什么?

完整的代码在这里:

#include

#include

#define USAGE"USAGE: ./huffman

"

FILE* openFile(char[]);

void parseRows(FILE*);

int countNumOfRows(FILE*);

void printOutput(char**, int);

int main(int argc, char** argv){

FILE* fd;

if (argc != 2) printf("%s", USAGE);

fd = openFile(argv[1]);

parseRows(fd);

}

FILE* openFile(char* file){

FILE* stream;

stream = fopen(file,"r");

return stream;

}

int countNumOfRows(FILE* file){

int i = 0;

char c;

while ((c=fgetc(file))!= EOF) {

if (c == '.') i++;

}

printf("numero di righe %d

", i);

return i;

}

void parseRows(FILE* file){

int c;

int numOfRow = 0;

int numOfChar = 0;

int numOfRows = countNumOfRows(file);

fseek(file, 0, SEEK_SET); // Reset file pointer position to the beginning

char **rows = malloc(numOfRows*sizeof(char*));

for (int i=0; i < numOfRows; i++) rows[i] = malloc(1000*sizeof(char));

while ((c=fgetc(file))!= EOF) {

if (c != '.') {

rows[numOfRow][numOfChar] = (char)c;

numOfChar++;

} else {

rows[numOfRow][numOfChar] = '\0';

numOfRow += 1;

numOfChar = 0;

}

}

printOutput(rows, numOfRows);

}

void printOutput(char** matrix, int rows){

for (int i=0; i

printf("%s", matrix[i]);

}

}

输入文件textFile.txt的示例:

Any text that contains more than one sentence.

This Should get parsed and return a 2 dimension array with every sentence as single array.

请显示输入文件示例以及最小的可复制示例。

我认为那正是我所做的? numOfRow初始化为0,并在每次发现句子时在else语句中增加

为什么不使用fgets? 您正在尝试一次读取整行。

我不知道该放什么尺寸...我将如何使用fgets在点之间拆分?

好吧,您可以标记.上返回的那一行...尽管我确实被误解了,所以这样做可能不值得。 至于大小,为什么不1000?

您的countNumOfRows()函数对文件中的点进行计数,然后使用该数字为数组分配空间。 但是,在最后一个点之后和EOF之前可能还有更多的字符(例如CR或LF或CRLF),因此您可以轻松地在已分配内存的末尾进行写入。

尝试:

return (i + 1)

在countNumOfRows()的末尾,看看是否消除了段错误。

错误仍然存在。 我试图分配char **rows = malloc(1000*sizeof(char*));并使用具有2行的txt文件来确定并且错误仍然存在。

你是救星。 谢谢!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值