[英]Check for carriage return at the end of a file
我有一个文本文件。 我必须检查以确保文件以回车符结束。 如果它没有以一个结尾,那么我想插入一个。 该文件现在具有正确的格式,我可以使用它进行进一步的解析。 它应该适用于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)组合结束。
看我准备了一个文件
FILE *b = fopen("jigar.txt","w");
fprintf(b,"jigar\r");
fclose(b);
现在我再次打开该文件进行检查
b = fopen("jigar.txt","r");
char f;
转到文件末尾
while(fscanf (b, "%c", &f) != EOF);
前一个字节
fseek( b,-1,1);
读那个字节
fscanf(b,"%c",&f);
核实
if(f == 13) \\ here instead of 13 you can writr '\r'
printf("\r is detected");
else
write \r to file...
#include <stdio.h>
void main()
{
FILE *file = fopen("me.txt", "r+"); // A simple text file created using vim
char buffer[100] ;
fseek(file, -2, SEEK_END); // Fetches the last 2 characters of the file
fread(buffer,1,2,file); // Read the last 2 characters into a buffer
printf("\n Character is %s",buffer); // Will print the entire contents of the buffer . So if the line ends with a "\n" we can expect a new line to be printed
//Since i am interested to know how the line feeds & Carriage returns are added to the end of the file , i try to print then both . I have run this code under Suse Linux and if i press enter key after the last line in the file i get two "\n" in the output . I confirmed this using GDB . I would like to run in a Windows environment and check how the behavior changes if any .
printf(" --is %c",buffer[1]);
printf(" --is %c",buffer[2]);
if(buffer[1]=='\r' || buffer[2]=='\n')
//take action
else
// take another action
fclose(file);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.