1

字符串长度没有得到正确的长度,所以程序的其余部分不起作用。我正在尝试每行读取 62 个字符,然后用另外 62 个字符打印一个新行。

谁能帮我正确地将字符数组传递给输出函数?

#include <stdio.h>
#include <string.h>

#define _CRT_SECURE_NO_DEPRECATE

void output(char *wbuf, char *lbuf, int lineLength);
void readFile(FILE *getty, char *wbuf, char *lbuf);

FILE *getty;

int main(void) {
    char wbuf[1000] = {0}, lbuf[1000] = {0};

    if (fopen_s(&getty,"getty.txt", "r") != 0 ) 
    {
        printf("Failed to open getty.txt for reading.");
    } else {
        readFile(getty, wbuf, lbuf);
    }

    fclose(getty);
    return 0;
}

void readFile(FILE *getty, char *wbuf, char *lbuf) 
{
    static int lineLength = 62;
    while (!feof(getty)) 
    {
        fscanf(getty, "%s", wbuf);
        output(wbuf, lbuf, lineLength);     
    }
}

void output(char *wbuf, char *lbuf, int lineLength) 
{
    int wbufLength, lbufLength, i = 0;

    wbufLength = strlen(wbuf);
    lbufLength = strlen(lbuf);
    //prints incorrect
    printf("wbuflength %d lbuflength %d\n", wbufLength, lbufLength); 
    // lengths
    if ( (wbufLength + lbufLength) <= lineLength) 
    {                  
        strcat(lbuf,wbuf);  //lbuf should be 0 but it starts at
    }                       //274, wbuf not correct either
    else 
    {
        strcat(lbuf,"\n");
        lineLength += 62;
        strcat(lbuf, wbuf);
    }
}
4

1 回答 1

0

问题是你的循环条件:

while (!feof(getty)) { ... }

直到输入操作失败才会设置 EOF 标志。

在您的情况下,循环循环,然后fscanf操作失败,因为它位于文件的末尾,但您没有在循环内检查它,然后output即使没有从文件中读取任何内容,您也会调用。然后循环继续,然后它注意到文件已到达 EOF。

于 2013-07-01T18:45:28.140 回答