Reading and writing to a file matlab - file

I want to read data from a file and save it into an array. Then insert some new data into this array and then save this new data back into the same file deleting what is already there. My code works perfectly, giving me my required data, when I have 'r+' in the fopen parameters, however when I write to the file again it does not delete the data already in the file just appends it to the end as expected. However when I change the permissions to 'w+' instead of 'r+', my code runs but no data is read in or wrote to the file! Anyone know why this might be the case? My code is as seen below.
N = 1021;
b = [0;0;0;0;0];
% Opens file specified by user.
fid = fopen('testing','w+');
% Read header data
Header = fread(fid, 140);
% Move to start of data
fseek(fid,140,'bof');
% Read from end of config header to end of file and save it in an array
% called data
Data = fread(fid,inf);
Data=reshape(Data,N,[]);
b=repmat(b,[1 size(Data,2)]);
r=[b ; Data];
r=r(:);
r = [Header;r];
% write new values into file
fwrite(fid,r);
fclose(fid);
% Opens file specified by user.
fid = fopen('test');
All = fread(fid,inf);
fclose(fid);

According to the documentation, the w+ option allows you to "Open or create new file for reading and writing. Discard existing contents, if any." The contents of the file are discarded, so Data and Header are empty.

You need to set the position indicator of the filehandle before writing. With frewind(fid) you can set it to the beginning of the file, otherwise the file is written / appended at the current position.
N = 1021;
b = [0;0;0;0;0];
% Opens file specified by user.
fid = fopen('testing','r+');
% Read header data
Header = fread(fid, 140);
% Move to start of data
fseek(fid,140,'bof');
% Read from end of config header to end of file and save it in an array
% called data
Data = fread(fid,inf);
Data=reshape(Data,N,[]);
b=repmat(b,[1 size(Data,2)]);
r=[b ; Data];
r=r(:);
r = [Header;r];
% write new values into file
frewind(fid);
fwrite(fid,r);
fclose(fid);
% Opens file specified by user.
fid = fopen('test');
All = fread(fid,inf);
fclose(fid);

Related

Create text file to write/add of a couple of images name

I tried to get a script to create a text file that could write/add the images name, but the function
FileID = CreateFileForWriting(filename) does not work, it shows that was used by other process
I did not get this, is this function not right format or something is wrong, thx
Number Totaln
totaln=countdocumentwindowsoftype(5)
String filename, text
Number fileID
if (!SaveasDialog( "save text file as",getapplicationdirectory(2,0) + "Imagename.txt", filename))exit(0)
fileID = CreateFileForWriting(filename)
number i
for(i = 0; i <totaln; i++)
{
image imgSRC
imgSRC := GetFrontImage()
string imgname=getname(imgSRC)
WriteFile(fileID,"imgname")
Result("imgname")
}
Your code is nearly fine, but if you use the low-level API for file I/O you need to ensure that you close files you've opened or created.
Your script doesn't. Therefore, it runs fine exactly 1 time but will fail on re-run (when the file is still considered open.)
To fix it, you need to have closefile(fileID) at the end.
( BTW, if you script exits or throws after opening a file but before closing it, you have the same problem. )
However, I would strongly recommend not using the low-level API but the file streaming object instead. It also provides an automated file-closing mechanism so that you don't run into this issue.
Doing what you do in your script would be written as:
void writeCurrentImageNamesToText()
{
number nDoc = CountImageDocuments()
string filename
if (!SaveasDialog( "save text file as",getapplicationdirectory(2,0) + "Imagename.txt", filename)) return
number fileID = CreateFileForWriting(filename)
object fStream = NewStreamFromFileReference(fileID,1) // 1 for auto-close file when out of scope
for( number i = 0; i <nDoc; i++ ){
string name = GetImageDocument(i).ImageDocumentGetName()
fStream.StreamWriteAsText( 0, name + "\n" ) // 0 = use system encoding for text
}
}
writeCurrentImageNamesToText()

Lua Read File and Write to New File

I need to copy a file and change the extension from .seq to mid (without using shell commands)
This works
file = io.open(source_filename, "rb")
source_content = file:read("*all")
file = io.open(source_filename ..".mid", "wb")
file:write(source_content)
file:close()
and I get Song.seq.mid
but I would like Song seq.mid
if I do a
source_filename = string.gsub(source_filename, ".seq", ".mid")
file = io.open(source_filename, "wb")
then file has a nil value file:write(source_content)
You can modify source_filename before opening the file for writing: source_filename = source_filename:gsub("seq$", "mid"). This will replace seq at the end of the filename with mid, achieving the desired effect.

Matlab: copy array in file txt

I want to copy elements of an array in a file txt. I read the first 50 samples of a wav file in array a and I want to copy a in a file txt. This is my code:
[s,fs]=wavread('file.wav');
for k=1:50
a=s(k)
end
fid = fopen('file.txt','wt');
fprintf(fid,'%f\n',a);
fclose(fid);
With this code in file txt there is only the last element of a, not all samples.
fprintf can process vector input. So you can simply replace the loop by a = s(1:50);:
[s,fs]=wavread('file.wav');
a = s(1:50);
fid = fopen('file.txt','wt');
fprintf(fid,'%f\n',a);
fclose(fid);

File to Array in Lua

I was wondering how do I get a line into an array with lua in some sort of function
eg. FileToArray("C:/file.txt")?
I know I can use:
var = io.open("file")
Data = var:read()
But it only returns the 1st line, and no other lines.
Anyone know how to fix this or a different way? I'm new to lua and the file system stuff.
You can pass "*a" to read function, it should read the whole file:
local file = io.open("file-name", "r");
local data = file:read("*a")
And if you want to store each line in an array. Like Jane's solution you can use
io:lines () - which returns iterator function (each call gives you a new line)
local file = io.open("file-name", "r");
local arr = {}
for line in file:lines() do
table.insert (arr, line);
end
local file = io.open("c:\\file.txt")
local tbllines = {}
local i = 0
if file then
for line in file:lines() do
i = i + 1
tbllines[i] = line
end
file:close()
else
error('file not found')
end
See: http://lua-users.org/wiki/IoLibraryTutorial for more information.

Matlab command to access the last line of each file?

I have 20 text files, and I want to use a matlab loop to get the last line of each file without taking into consideration the other lines. is there any matlab command to solve this problem?
One thing you can try is to open the text file as a binary file, seek to the end of the file, and read single characters (i.e. bytes) backwards from the end of the file. This code will read characters from the end of the file until it hits a newline character (ignoring a newline if it finds it at the very end of the file):
fid = fopen('data.txt','r'); %# Open the file as a binary
lastLine = ''; %# Initialize to empty
offset = 1; %# Offset from the end of file
fseek(fid,-offset,'eof'); %# Seek to the file end, minus the offset
newChar = fread(fid,1,'*char'); %# Read one character
while (~strcmp(newChar,char(10))) || (offset == 1)
lastLine = [newChar lastLine]; %# Add the character to a string
offset = offset+1;
fseek(fid,-offset,'eof'); %# Seek to the file end, minus the offset
newChar = fread(fid,1,'*char'); %# Read one character
end
fclose(fid); %# Close the file
On Unix, simply use:
[status result] = system('tail -n 1 file.txt');
if isstrprop(result(end), 'cntrl'), result(end) = []; end
On Windows, you can get the tail executable from the GnuWin32 or UnxUtils projects.
It may not be very efficient, but for short files it can be sufficient.
function pline = getLastTextLine(filepath)
fid = fopen(filepath);
while 1
line = fgetl(fid);
if ~ischar(line)
break;
end
pline = line;
end
fclose(fid);

Resources