N
N
NikitaWeb2019-10-25 22:23:31
C++ / C#
NikitaWeb, 2019-10-25 22:23:31

How to translate code from Linux to Windows?

There is such a code

#include <errno.h>
#include <stdio.h>
#include <fcntl.h>

int main()
{
  	int actlen;
  	int hfile, hl;
  	char fname[]  = "text.txt";
  char buf[100] = "";
  	struct flock lock = {F_WRLCK,SEEK_SET, 0, 0};

  printf("\033[4;30;45m\033[20;33HHello!\n");
  printf("\033[21;33HLAB4: Block files\n");

  	fflush(stdout);
  	
  hfile = open(fname, O_RDWR, NULL);
  if ( hfile == -1 )
   	{
   		if (errno == EACCES) printf("\033[22;33HFile access denied!\n");
    else  		     printf("\033[22;33HFile not found!\n");
    printf("\033[0m"); 
   		return 1;   
   	}

  	printf("\033[0m");
  	hl = fcntl(hfile, F_SETLK, &lock);
  	if (hl==-1)
   	{
   		printf("\033[2J\033[1;34;42m\033[1;24H");
   		printf("File lock not permitted! Wait...\n");
   		fcntl(hfile, F_SETLKW, &lock);
   	}
  
  	printf("\033[2J\033[1;31;44m\033[1;24H");
  	printf("File lock permitted! Please press <ENTER>.\n");
  	fflush(stdout);
  	getchar();
  
  	printf("\033[12;32H");
  	actlen = read(hfile, buf, 80);
  	write(1, buf, actlen);
  printf("\033[0m"); 
  	printf("\nPress <Enter> for exit!\n");
  	fflush(stdout);
  	getchar();
   
  	lock.l_type=F_UNLCK;
  	if (fcntl(hfile, F_SETLK, &lock)==-1)
   	{
   		printf("File not unlocked!");
   		printf("\033[0m\033[2J");
   		close(hfile);
   		return 1;
   	}
  	printf("\033[0m\033[2J"); 
  	close(hfile);
 }

It's under Linux.
What lines need to be changed for Windows? The problem is mainly because of the constants.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tsarevfs, 2019-10-25
@tsarevfs

Working with files under linux and windows occurs in different ways. Look for examples for WinAPI:
https://docs.microsoft.com/en-us/windows/win32/api...
Cross platform solution will have 2 sets of functions under ifdef directives.
If you just need to run it on a computer with Windows, then there are virtual machines or WSL. Then you can not rewrite anything, but work in a linux environment under windows.

C
CityCat4, 2019-10-25
@CityCat4

Handle I/O, file locking, and ESC sequences will not work in Windows (I'm not really sure about the latter). This example needs to be completely rewritten by reading MSDN.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question