gpt4 book ai didi

c - 输出中的奇怪行为

转载 作者:行者123 更新时间:2023-11-30 17:44:45 26 4
gpt4 key购买 nike

我的程序无法正常运行。

这是代码:

#include <stdio.h>
#include <stdlib.h> // for EXIT_SUCCESS and EXIT_FAILURE
#include <ctype.h>
#include <string.h>

void ReadFile(FILE* file) {
unsigned lines = 0;

int braces = 0;
int curlyBraces = 0;
int comments = 0;

int c;
char* line = 0;
unsigned col = 0;

while ((c = fgetc(file)) != EOF) {
if(c == '\n') { // new line
lines++;

printf("%4d: {%d} (%d) /*%d*/ |%s\n", lines, curlyBraces, braces, comments, line);
free(line); line = 0;
col = 0;
} else {
// add character to line
line = (char*)realloc(line, (col+1)*sizeof(char));
if (line == 0) {
fprintf(stderr, "error reallocating memory");
return;
}
line[col] = c;
col++;

if (c == '(') {
braces++;
} else if (c == ')') {
braces--;
} else if (c == '{') {
curlyBraces++;
} else if (c == '}') {
curlyBraces--;
} else if (c == '/') {
if (fgetc(file) == '*') {
comments++;
} else {
fseek(file, -1, SEEK_CUR);
}
} else if (c == '*') {
if (fgetc(file) == '/') {
comments--;
} else {
fseek(file, -1, SEEK_CUR);
}
}
}
}
}

int main(int argc, char** argv) {
short lines = 0, words = 0, chars = 0;

/* check for arguments */
if (argc == 1) {
fprintf(stderr, "usage: %s filename\n", argv[0]);
return EXIT_FAILURE;
}

/* open file */
FILE* file = fopen(argv[1], "r");
if(file == 0) {
fprintf(stderr, "error open file '%s'\n", argv[1]);
return EXIT_FAILURE;
}

ReadFile(file);

if (fclose(file) == EOF) {
fprintf(stderr, "error in fclose()\n");
return EXIT_FAILURE;
}

return EXIT_SUCCESS;
}

在输出中我得到一些奇怪的输出,比如 realloc 覆盖了一些数据......我已经尝试过 strcat,但不能使用常量字符。所以我必须使用 realloc。

这是输出的简短摘录

P 68: {1} (0) /*0*/ |   / open file *
69: {1} (0) /*0*/ | FILE* file = fopen(argv[1], "r");
70: {2} (0) /*0*/ | if(file == 0) {
rn EXIT_FA(0) /*0*/ | fprintf(stderr, "error open file '%s'\n", argv[1]);
r open fi (0) /*0*/ | return EXIT_FAILURE;
73: {1} (0) /*0*/ | }
} 74: {1} (0) /*0*/ |

也许还有另一种方法可以实现这一点?使用 fgets() 我可以获得整行,但增加文件中的指针,并且我必须给 fgets() 一个字符计数。所以这不是完美的解决方案。

最佳答案

在打印字符串之前,您需要终止字符串:

    lines++;
line[col] = 0; // new
printf("%4d: {%d} (%d) /*%d*/ |%s\n", lines, curlyBraces, braces, comments, line);

不幸的是line[col]在这里超出范围。因此,在添加终止符之前,您需要 realloc 行,如下所示:

        lines++;
line = (char*)realloc(line, (col+1)*sizeof(char));
if (line == 0) {
fprintf(stderr, "error reallocating memory");
return;
}
line[col] = 0; // new
printf("%4d: {%d} (%d) /*%d*/ |%s\n", lines, curlyBraces, braces, comments, line);

另外,你知道ungetc吗?您可以将那些 fseek(-1) 替换为 ungetc。

关于c - 输出中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19866054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com