在Linux上使用与fgets()读取文件,DOS行结束 [英] Reading files with DOS line endings using fgets() on linux

查看:1015
本文介绍了在Linux上使用与fgets()读取文件,DOS行结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我收到在运行时DOS行结尾的文件,所以我不能转换行结束到UNIX风格下线。另外,我的应用程序在Windows和Linux上运行。我的应用程序的与fgets()上的文件,并试图在行由行阅读。

I have a file with DOS line endings that I receive at run-time, so I cannot convert the line endings to UNIX-style offline. Also, my app runs on both Windows and Linux. My app does an fgets() on the file and tries to read in line-by-line.

会在Linux上每行读取的字节数也占2尾随字符(\\ r \\ n)的或将只包含的(\\ n) 的和的 \\ r 的将由底层系统丢弃?

Would the number of bytes read per line on Linux also account for 2 trailing characters (\r \n) or would it contain only (\n) and the \r would be discarded by the underlying system?

编辑:

好了,该行结束而阅读在Linux上的文件pserved $ P $,但我遇到了另一个问题。在Windows中,打开该文件中的R或RB的行为不同。窗户是否清楚对待这两种模式,不像Linux呢?

Ok, so the line endings are preserved while reading a file on Linux, but I have run into another issue. On Windows, opening the file in "r" or "rb" is behaving differently. Does windows treat these two modes distinctly, unlike Linux?

推荐答案

与fgets()保持行结尾。

http://msdn.microsoft.com /en-us/library/c37dh6kf(v=vs.80).aspx

与fgets()本身不具有转换行尾的任何特殊选项,但在Windows中,您可以选择要么打开二进制模式下的文件,还是在文本模式。在文本模式下的Windows的CR / LF序列(C字符串:\\ r \\ n)转换成只是一个换行符(C字符串:\\ n)。这是一个功能,让你可以写同样的code用于Windows和Linux,它会工作(你不需要为\\ r \\ n在Windows上,只是\\ n在Linux上)。

fgets() itself doesn't have any special options for converting line endings, but on Windows, you can choose to either open a file in "binary" mode, or in "text" mode. In text mode Windows converts the CR/LF sequence (C string: "\r\n") into just a newline (C string: "\n"). It's a feature so that you can write the same code for Windows and Linux and it will work (you don't need "\r\n" on Windows and just "\n" on Linux).

http://msdn.microsoft.com/en-美国/库/ yeby3zcb(v = VS.80

请注意,Windows调用 fopen()函数采用相同的参数调用 fopen()函数中Linux操作系统。 二进制模式需要一个非标准的字符('B')的文件模式,但文本模式是默认的。所以,我建议你只使用Windows和Linux一样code线; 的Windows版本fopen()函数是专为。

Note that the Windows call to fopen() takes the same arguments as the call to fopen() in Linux. The "binary" mode needs a non-standard character ('b') in the file mode, but the "text" mode is the default. So I suggest you just use the same code lines for Windows and Linux; the Windows version of fopen() is designed for that.

Linux版本的C库中没有任何棘手的特点。如果文本文件具有CR / LF行结束符,那就是当你读它你会得到什么。 Linux的 fopen()函数将在选择接受'B',但忽略了!

The Linux version of the C library doesn't have any tricky features. If the text file has CR/LF line endings, then that is what you get when you read it. Linux fopen() will accept a 'b' in the options, but ignores it!

http://linux.die.net/man/3/fopen

http://linux.die.net/man/3/fgets

这篇关于在Linux上使用与fgets()读取文件,DOS行结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆