【发布时间】:2016-03-04 17:05:54
【问题描述】:
该程序从文件 RDLRDLLLL 读取到缓冲区,然后传输到 char 数组,最终将每个字符转换为伪代码。问题是:它还读取了一些奇怪的字符,所以我的问题是:问题出在哪里?
#define n 100
void main() {
int i;
char tablou_init[n];
FILE *fp;
long lSize;
char *buffer;
fp = fopen("date.in", "r");
if (!fp) perror("date.in"), exit(1);
fseek(fp, 0L, SEEK_END);
lSize = ftell(fp);
rewind(fp);
/* allocate memory for entire content */
buffer = calloc(1, lSize + 1);
if (!buffer) fclose(fp), fputs("memory alloc fails", stderr), exit(1);
/* copy the file into the buffer */
if (1 != fread(buffer, lSize, 1, fp)) fclose(fp), free(buffer), fputs(
"entire read fails", stderr), exit(1);
strcpy(tablou_init, buffer);
for (i = 0; i < n; i++) {
if (tablou_init[i] == 'R') printf("<program>\n");
else if (tablou_init[i] == 'D') printf("<secventa de instructiuni>\n");
else if (tablou_init[i] == 'L') printf("<consecutivitate de descrieri>\n");
else if (tablou_init[i] == 'T') printf("<tip>\n");
else if (tablou_init[i] == 'I') printf("<lista de identificatori>\n");
else if (tablou_init[i] == 'S') printf("<consecutivitate de instructiuni>\n");
else if (tablou_init[i] == 'A') printf("<instructiunea de Atribuire>\n");
else if (tablou_init[i] == 'F') printf("<instructiunea IF>\n");
else if (tablou_init[i] == 'H') printf("<instructiune>\n");
else if (tablou_init[i] == 'W') printf("<instructiunea WHILE>\n");
else if (tablou_init[i] == 'i') printf("<identificator>\n");
else if (tablou_init[i] == 'e') printf("<expresie>\n");
}
fclose(fp);
free(buffer);
for (i = 0; i < n; i++) {
printf("%c", tablou_init[i]);
}
}
【问题讨论】:
-
garbage in,garbage in,请正确缩进你的代码!
-
哇。那些带有所有逗号的行 - 确定它有效,但它与“正常”相距甚远,很多人会打电话给你!
-
这会给你一个 F:
fclose(fp),fputs("memory alloc fails",stderr),exit(1); -
是的,我知道,我可以使用另一个数组,但是!它确实更容易看到我想要做什么,而且它也是查看程序如何工作的原型
-
发布观察到的输出比描述它更有用:“它也读取一些奇怪的字符”。