gpt4 book ai didi

c - 文件崩溃导致的 Windows 大写转换

转载 作者:可可西里 更新时间:2023-11-01 11:18:39 27 4
gpt4 key购买 nike


下面的代码应该将文件的内容转换为大写(如果需要转换,它会将原始字符替换为大写)。该代码适用于 Mac OS 和 Linux。但是在 Windows 上,转换在第二个字母处停止并将第二个字母(大写)写入文件中,永不结束。

例子

源数据:阿斯达夫
结果:ASSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS...

我不明白,为什么它在其他平台上工作,但适用于 Windows。

我非常感谢任何解释。

问候, eljobso

#include <stdio.h>
#include <stdlib.h>

int to_upper_file(FILE *fp)
{
char ch = ' ';

if (fp == NULL)
{
perror("Unable to open file");
exit(0);
}
else
{
while (ch != EOF)
{
ch = fgetc(fp);
if ((ch >= 'a') && (ch <= 'z'))
{
ch = ch - 32;
fseek(fp, -1, SEEK_CUR);
fputc(ch, fp);
}
}

}
fclose(fp);

return 0;
}


int main(void)
{
FILE *fp;
int status;
char filename[20];

printf("Enter filename:");
scanf("%s", filename);
fp = fopen(filename, "r+");

if(!fp)
{
printf("File error.\n");
exit(0);
}
else
{
status = to_upper_file(fp);

if (status == 0)
{
printf("Conversion success.\n");
}
if (status == -1)
{
printf("Conversion failure.\n");
}
}

return 0;
}

最佳答案

由于对 FILE * 操作的缓冲性质,在读写或读写之间切换时有必要执行文件定位操作或(对于后者)仅刷新.

来自MSDN documentation to fopen() :

When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). However, when you switch from reading to writing, the input operation must encounter an EOF marker. If there is no EOF, you must use an intervening call to a file positioning function. The file positioning functions are fsetpos, fseek, and rewind. When you switch from writing to reading, you must use an intervening call to either fflush or to a file positioning function.

要让您的代码满足此规则,您可能需要在放置字符后添加一个 0-seek,如下所示:

    fseek(fp, -1, SEEK_CUR);
fputc(ch, fp);
fseek(fp, 0, SEEK_CUR);

或者你也可以刷新文件:

    fseek(fp, -1, SEEK_CUR);
fputc(ch, fp);
fflush(fp);

还应该提到的是,应该对所有相关的系统调用进行错误检查。


更新:

来自 C11 标准(7.21.5.3/7 的 fopen 函数)(斜体 由我):

When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters endof- file. [...]

关于c - 文件崩溃导致的 Windows 大写转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23854501/

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