fgets in while循环

时间:2014-04-07 19:44:53

标签: c segmentation-fault fgets

下面的代码在while循环中的fgets调用中给出了一个分段错误(它没有到达while循环中的printf语句进行调试)。

我在这里显示了main(从命令行中获取args)和partOne函数的开始。

有什么想法吗?

int main(int lLen, char *fileName)
{
    Word* allWords = (Word*)malloc(sizeof(Word));
    int numwords = 0;

    /*Create char*'s for fileName.out and fileName.words*/
    char *newName = malloc(sizeof(char)*50);
    char *newName2 = malloc(sizeof(char)*50);

    FILE* inputFile = fopen(fileName, "r+"); /*open file for reading*/

    partOne(lLen, numwords, fileName, allWords, inputFile, newName);
    partB(numwords, fileName, allWords, newName2);

    return 0;
}

/*Function partOne reads in words from a file and tidies them up into a neatly-formatted paragraph based on passed line length*/
int partOne(int lLen, int numwords, char *fileName, Word *allWords, FILE* inputFile, char *newName)
{
    char *insPtr = (char*)malloc(sizeof(char)*50); /*Make insPtr for allWords[pos].word to point to*/
    char *insPtr2 = (char*)malloc(sizeof(char)*50); /*Make insPtr for allWords[pos].word to point to*/
    char *outputLine = (char*)malloc(sizeof(char)*100); /*Initialize the output line to nothing*/
    char *currentWord = (char*)malloc(sizeof(char)*50); /*Initialize current word to nothing*/
    int pos = 0; /*Current position for inserting into array*/
    FILE* outputFile = fopen(newName, "w+");

    newName = strcat(fileName, ".out"); /*Add extension to fileName*/

printf("In partOne\n");
    while(fgets(outputLine, 100, inputFile) != NULL) /*Get line*/
    {
        int cCount = 0; /*Number of characters in current line*/
        int flag = 0; /*Break for repetition*/
        int i = 0; /*Counter for repetition*/

printf("Top of while\npos=%d cCount=%d\n", pos, cCount);
        /*If not the first line, increment position*/
        if(pos > 0)
        {
            pos++;
        }

提前谢谢!!

0 个答案:

没有答案