Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created October 22, 2009 03:12
Show Gist options
  • Save shaobin0604/215687 to your computer and use it in GitHub Desktop.
Save shaobin0604/215687 to your computer and use it in GitHub Desktop.
检测系统换行符
/*
============================================================================
Name : test_lf_cr.c
Author : shaobin0604
Version :
Copyright : Your copyright notice
Description : This small piece of code is used to detect the new line character
on different platforms.
eg.
* Unix-like LF (0x0a)
* Mac CR (0x0d)
* Windows CR+LF (0x0d 0x0a)
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i;
int read;
FILE* fp;
if ((fp = fopen("file1", "w")) == NULL) {
printf("error open file file1!\n");
exit(1);
}
printf("1. write '\\n' to file\n");
fputc('\n', fp);
fclose(fp);
if ((fp = fopen("file1", "r")) == NULL) {
printf("error open file file1!\n");
exit(1);
}
printf("2. read file in text mode\n");
int c;
while (EOF != (c = fgetc(fp)))
printf("0x%02x ", c);
fclose(fp);
if ((fp = fopen("file1", "rb")) == NULL) {
printf("error open file file1!\n");
exit(1);
}
char data[2];
if (2 != (read = fread(data, sizeof(char), 2, fp))) {
if (ferror(fp)) {
printf("error read file file1!\n");
exit(1);
}
if (feof(fp)) {
/*
* do nothing, just swallow it
*/
}
}
printf("\n3. read file in binary mode\n");
for (i = 0; i < read; i++) {
printf("0x%02x ", data[i]);
}
fclose(fp);
printf("\n4. conclusion\n");
if (read == 2 && data[0] == (char) 0x0d && data[1] == (char) 0x0a) {
printf("the new line character on this platform is CR+LF\n");
} else if (read == 1) {
if (data[0] == (char) 0x0a)
printf("the new line character on this platform is LF\n");
else if (data[0] == (char) 0x0d)
printf("the new line character on this platform is CR\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment