How to read a text file into a char array

조회 수: 34 (최근 30일)
Paolo Binetti
Paolo Binetti 2017년 1월 22일
댓글: Paolo Binetti 2017년 1월 22일
This is probably trivial, but I have not found an easy way to convert a text file of n lines and m columns (sample attached) into a char array of the same shape. The only way that might work for me is an n-long for-loop of "fscanf", but I do not know n beforehand, and I figure there must be a simpler and faster vectorized command, which I ignore (I tried fileread and textread to no avail).

채택된 답변

Walter Roberson
Walter Roberson 2017년 1월 22일
temp = regexp(fileread('sample_input.txt'), '\r?\n', 'split');
output = vertcat(temp{:});
  댓글 수: 3
Walter Roberson
Walter Roberson 2017년 1월 22일
The \r represents carriage return. I did not bother to check whether your file has those or only newlines (and it is really easy end up accidentally having a mix of files) so I made the carriage return optional which is done by adding a ? after it.
An alternative to the \r?\n for your situation would be \W+ which would mean any sequence of consecutive non-"word" characters. That would also cover the case where you had multiple columns separated by blanks that you wanted to treat the same as if each were its own line.
Paolo Binetti
Paolo Binetti 2017년 1월 22일
Thank you, clear and useful.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by