首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

c语言初学者

2012-03-14 
c语言菜鸟求助读入一个文件(类型可能是txt/doc或者其他任意一种),按行与列存入二维数组。用户输入一个字符

c语言菜鸟求助
读入一个文件(类型可能是txt/doc或者其他任意一种),按行与列存入二维数组。用户输入一个字符串,在二维数组(原文件)查找,找到返回行号和列号。问题在于有的字符串(比如一个单词 可能是上一行和下一行都有)被分开在两行。求c实现。

[解决办法]

C/C++ code
#include <stdio.h>#include <malloc.h>#include <stdlib.h>#include <string.h>int* getLineInfo(){    FILE *fp;    char ch;    int *lineInfo, line = 0, count;    fp = fopen("out.txt", "r");    if(fp == NULL)        exit(1);    while(1)    {        ch = fgetc(fp);        if(feof(fp))            break;        if(ch == '\n')            ++line;    }    fseek(fp, 0, SEEK_SET);    lineInfo = (int*)malloc(sizeof(int)*(line+1));    lineInfo[0] = line;    line = 1;    count = 0;    while(1)    {        ch = fgetc(fp);        ++count;        if(feof(fp))            break;        if(ch == '\n')        {            lineInfo[line++] = count - 1;            count = 0;        }    }    fclose(fp);    return lineInfo;}void readFile(char *str){    FILE *fp;    char ch;    int i = 0;    fp = fopen("out.txt", "r");    if(fp == NULL)        exit(1);    while(1)    {        ch = fgetc(fp);        if(feof(fp))            break;        if(ch != '\n')            str[i++] = ch;    }    str[i] = '\0';    fclose(fp);}void getNextval(char *subStr, int *nextval, int length){    int i = 0, j = -1;    nextval[0] = -1;    while(i < length - 1)    {                if(j <= 0 || subStr[i] == subStr[j])        {            ++i;            ++j;            if(subStr[i] != subStr[j])                nextval[i] = j;            else                nextval[i] = nextval[j];        }        else            j = nextval[j];    }}int kmp(char *str, char *subStr){    int strLen = strlen(str);    int subStrLen = strlen(subStr);    int *nextval = (int*)malloc(sizeof(int)*subStrLen);    int i = -1, j = -1;    getNextval(subStr, nextval, subStrLen);    while(i < strLen && j < subStrLen)    {        if(j < 0 || str[i] == subStr[j])        {            ++i;            ++j;        }        else             j = nextval[j];    }    free(nextval);    if(j >= subStrLen)        return i - subStrLen;    return -1;}int main(){    int *lineInfo = getLineInfo();     char *str, find[] = "abc";    int i, sum = 0, pos;    for(i = 1; i <= lineInfo[0]; ++i)        sum += lineInfo[i];    str = (char*)malloc(sizeof(char)*(sum+1));    readFile(str);    //printf("%s\n", str);    pos = kmp(str, find) + 1;    if(pos == 0)        printf("未找到\n");    else    {        for(i = 1; i <= lineInfo[0]; ++i)        {            pos -= lineInfo[i];            if(pos <= 0)            {                pos += lineInfo[i];                printf("第%d行第%d列\n", i, pos);                break;            }        }    }    free(lineInfo);    free(str);    return 0;} 

热点排行