【发布时间】:2020-01-04 21:32:07
【问题描述】:
我正在尝试编写一个 C 程序来加载文件、读取文件并输出文件中最长的行以及符号数。结果写入另一个文件。代码似乎可以正常工作,但是我想了解为什么在稍微更改数组的定义以从maxLine 定义中删除等于空引号(= "")时会得到错误的结果。例如,如果我写以下内容:
char currentLine[100];
char maxLine[100];
然后我得到不想要的结果。
这是整个函数:
#define MAX_FILE_NAME 50
void maxCharRow()
{
FILE *fptr;
errno_t err;
char fileNameRead[MAX_FILE_NAME] = "test.txt";
char fileNameWrite[MAX_FILE_NAME] = "results.txt";
char currentLine[100];
char maxLine[100] = "";
if ((err = fopen_s(&fptr, fileNameRead, "r")) != NULL) {
printf("Could not open the file: %s\n", fileNameRead);
exit(1);
}
while (fgets(currentLine, sizeof(currentLine), fptr) != NULL)
{
if (strlen(maxLine) < strlen(currentLine))
{
strcpy_s(maxLine, currentLine);
}
}
printf("\nLongest line in file has %i symbols\nand its content is:%s", strlen(maxLine), maxLine);
((err = fopen_s(&fptr, fileNameWrite, "w")) != NULL); {
fprintf(fptr, "%s", maxLine);
exit(1);
}
fclose(fptr);
}
【问题讨论】:
-
if (strlen(maxLine)...需要maxLine被初始化,如果你只是这样做char maxLine[100];则不是 -
with
char maxLine[100] = "";最终得到一个数组,其中所有 100 个元素都是'\0';使用char maxLine[100];,你最终会得到一个数组,其中元素的内容可以是任何东西(甚至,在奇怪的架构中,可能是非法的)。 -
这个
strcpy_s(maxLine, currentLine);看起来不对。这个函数应该用三个参数调用:port70.net/~nsz/c/c11/n1570.html#K.3.7.1.3 -
它可能看起来有问题,但是当您不指定大小时,它就像 strcpy 一样正常工作。我使用它只是因为 Visual Studio 不喜欢 strcpy。