I have a text file. I have to check to ensure 开发者_如何学Cthat the file is ending with a Carriage return. If it is not ending with one then I would like to insert one. The file now being of the correct format I can use it for further parsing. It should work in both Windows & Linux environments.
Try something like this (not tested):
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);
Note: Are you sure you mean 0x0D? In Linux, lines are ended by 0x0A (\n) and in Windows by the combination 0x0D 0x0A (\r\n).
see i have prepare one file
FILE *b = fopen("jigar.txt","w");
fprintf(b,"jigar\r");
fclose(b);
now i have again open that file for checking
b = fopen("jigar.txt","r");
char f;
go to end of file to last
while(fscanf (b, "%c", &f) != EOF);
go 1 byte previous
fseek( b,-1,1);
read that byte
fscanf(b,"%c",&f);
check it
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);
}
精彩评论