Borrar filtros
Borrar filtros

Can a file be opened by two different programs simultaneously?

13 visualizaciones (últimos 30 días)
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

Walter Roberson
Walter Roberson el 18 de Nov. de 2021
If you are using Windows, then it has mandatory locking, and a file that is opened for writing by one process cannot be opened for reading by a different process — not unless the writing process deliberately makes the file readable.
Linux and Mac work differently.
  3 comentarios
Walter Roberson
Walter Roberson el 20 de Nov. de 2021
Maybe? I would not rule out the possibility of there being a .NET method of doing it that you could invoke from MATLAB. Certainly no Mathworks provided methods.
If you were to use memmapfile() then possibly those would be automatically shared, maybe? But you cannot use the same i/o calls required by the assignment if you use those functions.
Walter Roberson
Walter Roberson el 20 de Nov. de 2021
If you do not have access to the file unlocking system, then work-around for windows to prevent conflicts and be reliable, is to use a different file for each turn for each side.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by