Can a file be opened by two different programs simultaneously?
Mostrar comentarios más antiguos
Hi I'm making a simple shooter game in matlab for a school project and I'm wondering if two different instances of a program can access a file simultaneously? It's a two player game and the two players can only communicate through files using fscanf and fprintf which is a requirement. So player 1 moves, writes his position to his file, and player 2 will read that position from player 1's file so he knows where to draw the enemy character. Player 1 is the only one who can write to his file, the same applies to player 2.
I was running into issues where sometimes a player can't read a valid number from the file and I assumed that whenever a player is writing to his file, the other player can't access it. I solved the issue with a while loop to continuously try and grab a number until it is valid. Am I wrong in thinking that a file can't be read from whilst it's currently being written to?
Code:
function [num] = readNum(fname,size,formatSpec)
%readNum reads numerical data from file
%Input Arguments
% fname - name of file passed from main function
% size - size of array being read
% formatSpec - format specifier
%Output Arguments
% num - number can be a scalar, vector, or matrix
fin = fopen(fname,'r');
%only close file when valid number is read
%It waits until file is no longer being written to
num = fscanf(fin,formatSpec,size)';
while isempty(num)
close(fin)
fin = fopen(fname,'r');
num = fscanf(fin,formatSpec,size)';
end
fclose(fin);
end
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Historical Contests en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!