c html file,C programming task, html source file

博客探讨了C语言中字符数组处理字符串时需要添加零终止符的问题,以及feof()函数使用不当可能导致的错误。文章提供了正确的读取文件并确保字符串正确打印的代码示例,并强调了在遇到EOF时检查错误的重要性。
摘要由CSDN通过智能技术生成

You are missing to zero-terminate the char-array to enable it to be handle as a string before printing it.

Mod you code either like so:

...

{

char key[18 + 1]; /* add one for the zero-termination */

memset(key, 0, sizeof(key)); /* zero out the whole array, so there is no need to add any zero-terminator in any case */

...

or like so:

...

{

char key[18 + 1]; /* add one for the zero-termination */

... /* read here */

key[18] = '\0'; /* set zero terminator */

printf("\n%s", key);

...

Update:

As mentioned in my comment to your question there is "another story" related to the way feof() is used, which is wrong.

Please see that the read loop is ended only after an EOF had been already been read in case of an error or a real end-of-file. This EOF pseudo character, then is added to the character array holdling the reads' result.

You might like to use the following construct to read:

{

int c = 0;

do

{

char key[18 + 1];

memset(key, 0, sizeof(key));

size_t i = 0;

while ((i < 18) && (EOF != (c = fgetc(src_file))))

{

key[i] = c;

printf("%c", key[i]);

i++;

}

printf("\n%s\n", key);

} while (EOF != c);

}

/* Arriving here means fgetc() returned EOF. As this can either mean end-of-file was

reached **or** an error occurred, ferror() is called to find out what happend: */

if (ferror(src_file))

{

fprintf(stderr, "fgetc() failed.\n");

}

For a detailed discussion on this you might like to read this question and its answers.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值