我有一个文本文件。我必须检查以确保文件以回车符结尾。如果它不是以 1 结尾,那么我想插入一个。该文件现在具有正确的格式,我可以使用它进行进一步解析。它应该可以在 Windows 和 Linux 环境中工作。
最佳答案
尝试这样的事情(未测试):
FILE *file = fopen(path, "r+");
char c;
fseek(file, -1, SEEK_END);
fread(&c, 1, 1, file);
if (c != '\r') { /* This will work on Win/Linux and also on a Mac */
fseek(file, 0, SEEK_END);
fprintf(path, "\r");
}
fclose(file);
注意:您确定您的意思是 0x0D 吗?在 Linux 中,行以 0x0A (\n) 结束,在 Windows 中以组合 0x0D 0x0A (\r\n) 结束。
关于检查文件末尾是否有回车符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7307255/