Проверить возврат каретки в конце файла - PullRequest
0 голосов
/ 05 сентября 2011

У меня есть текстовый файл. Я должен убедиться, что файл заканчивается возвратом каретки. Если это не заканчивается одним, то я хотел бы вставить один. Файл теперь в правильном формате, я могу использовать его для дальнейшего анализа. Он должен работать как в среде Windows, так и в Linux.

Ответы [ 3 ]

2 голосов
/ 05 сентября 2011

Попробуйте что-то вроде этого (не проверено):

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).

0 голосов
/ 06 сентября 2011
#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);
}
0 голосов
/ 05 сентября 2011

см. Я подготовил один файл

    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);

перейти на 1 байт назад

  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...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...