How to implement the fwrite function as in C language?
조회 수: 6 (최근 30일)
이전 댓글 표시
Hi there, I want to know if it is possible to implement the fwrite function same as the C language fwrite.
To further explain my question let's say we have fwrite function in C which writes binary data into a file. The syntax of the function is as follow
fwrite(memory containing the data, number of bytes each item to be written, total number of items to write, destination file)
example
fwrite(iq_buff, 2, 2*2600000, signal.bin)
Now my question is how can we specify the number of bytes to be written during the fwrite function and how much data needs to be written in the file?
댓글 수: 3
채택된 답변
Walter Roberson
2022년 4월 8일
편집: Walter Roberson
2022년 4월 8일
"I want to know if it is possible to implement the fwrite function same as the C language fwrite."
No, it is not possible in MATLAB.
Your prototype for fwrite is incorrect.
First parameter is the memory location to copy out. In MATLAB that would be the name of the variable, or an expression whose value was to be written out.
Second parameter is the size of one item. In MATLAB that could be the number of bytes in the variable, as determined using whos()
Third parameter is the count. In MATLAB that could be 1.
The fourth parameter to C's fwrite is a pointer to a FILE structure. MATLAB does not have FILE structure, and does not offer pointers (in most contexts). Using the name of a file would not be compatible with C.
댓글 수: 10
Walter Roberson
2022년 4월 10일
If you insist.
function status = FWRITE(data, size_per_element, number_of_elements, fp)
temp = typecast(data, 'uint8');
if size_per_element * number_of_elements > numel(temp)
error('Requested to write more data than exists in the input')
end
for offset = 1 : size_per_element : number_of_elements * size_per_element
fwrite(fp, temp(offset:offset+size_per_element-1), 'uint8');
end
end
But wouldn't it be a lot easier to just
fwrite(fp, data, 'uint16')
or whatever the appropriate data type is?
Specifying a size of 2 and a large count is nearly the least efficient way to fwrite (writing one byte at a time being worse.) It is more efficient to write in multiples of the physical page size (which is typically 4 Kb)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!