Debian Codegraph @

texk/texlive/windows_wrapper/wtestopenfiles.c

raw
1 /***********************************************************
2
3 This program tries to prevent doomed update attempts on windows by testing
4 whether all files concerned can be opened with exclusive read/write access.
5
6 This file is written in 2022 by Siep Kroonenberg and is placed
7 in the Public Domain.
8
9 ***********************************************************/
10
11 #include <windows.h>
12 #include <stdio.h>
13
14 int main( int argc, char *argv[] ) {
15 HANDLE hf;
16 char buf[MAX_PATH];
17 int ok = 1;
18 int chatty = 0;
19 int i;
20
21 if( argc > 1 ) {
22 for( i=1;i<argc;i++ ) {
23 if( argv[i][1] == 'v' ) {
24 chatty = 1;
25 } else {
26 puts( "This program reads a list of absolute filepaths from stdin" );
27 puts( "and errors out if any of them cannot be opened with" );
28 puts( "exclusive read/write access." );
29 puts( "A -v option produces status output on stdout." );
30 exit( 1 );
31 }
32 }
33 }
34
35 while ( fgets( buf, MAX_PATH, stdin )) {
36 buf[strlen(buf)-1] = '\0';
37 if (buf[0] != '\0') {
38 // buf represents a filepath
39 hf = CreateFile(
40 buf,
41 GENERIC_READ | GENERIC_WRITE,
42 0, // not shared
43 NULL,
44 OPEN_EXISTING,
45 FILE_ATTRIBUTE_NORMAL,
46 NULL
47 );
48 // OPEN_ALWAYS: creates missing file
49 // OPEN_EXISTING: can fail with ERROR_FILE_NOT_FOUND
50 if( hf == INVALID_HANDLE_VALUE ) {
51 if( GetLastError() == ERROR_FILE_NOT_FOUND ) {
52 if( chatty ) printf( "%s not present, is ok\n", buf );
53 continue;
54 } else {
55 ok = 0;
56 if( chatty ) printf( "%s present, but cannot be opened\n", buf );
57 break;
58 }
59 } else {
60 if( chatty ) printf( "%s can be exclusively opened, is ok\n", buf );
61 CloseHandle( hf );
62 }
63 }
64 }
65 if( ok ) {
66 if( chatty ) puts( "ok" );
67 exit(0);
68 } else {
69 if( chatty ) puts( "not ok" );
70 exit( 1 );
71 }
72 }