Windows/Linux file reading with regexp inconsistency?

조회 수: 2 (최근 30일)
Zhangxi Feng
Zhangxi Feng 2019년 10월 8일
댓글: Walter Roberson 2019년 10월 9일
In my program, I am reading an input text file using the following code:
file = fileread(GAFname);
fileText = regexp(file, '\r\n|\r|\n', 'split')';
The text file can be anything, in this case let's use:
A
B
C
D
E
The text file is created in windows using notepad++. When executing this code on windows, it splits up file into 5x1 cells perfectly. But when the same files are transferred to a Linux workstation, it suddenly makes a 6x1 cell array with the last one being empty.
Does anyone know if this is related to regexp, creation of the text file (i.e. windows vs linux in terms of \r and \n), or is this caused by something else? Could it be because the version of MATLAB on the Linux workstation is 2018b?
I tried the following: I copied all but the last line into a Linux text editor and then manually entered the last line in the Linux editor then saved. It does not fix the problem so maybe it is not due to windows vs Linux text editors.
Thanks!
Jesse

채택된 답변

Walter Roberson
Walter Roberson 2019년 10월 8일
An empty one at the end is expected if the file ends with newline. It is the old question of whether newline is the line terminator or the line separator. The unix specs are clear that it is a separator. The Windows specs for text mode with CR+LF were traditionally that it was a terminator.
  댓글 수: 4
Zhangxi Feng
Zhangxi Feng 2019년 10월 8일
Thank you very much for the detailed response!
I now understand this system much better but probably should just stick with fopen and other file IO options in general, unless they also have similar problems?
Walter Roberson
Walter Roberson 2019년 10월 9일
Just assume that the file might or might not end in linefeed no matter how you read it, so do the test for isempty that I show.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Live Scripts and Functions에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by