Sys types h windows

Cannot open source file “sys/types.h” , “sys/stat.h”

I am using Visual Studio 2017. I just updated it and started to get this error on every project I have:

C++ cannot open source file «sys/types.h»
C++ cannot open source file «sys/stat.h»

Didn’t find any similar questions so sorry if duplicated. The error is for this 2 lines in file wchar.h and the error code is E1969 for both errors, tried repairing but didn’t work, any help would be appreciated!

4 Answers 4

With Visual Studio 2019 CE the path is

I was getting this error when I opened a project made by someone else in an older version of Visual Studio. Here is how I solved it:

Go to Project > [Project name] Properties.

Click VC++ Directories

Select Include Directories then Click the drop-down arrow to the right and select Edit.

Click New Line icon (looks like new folder icon)

Click the . to browse for a directory

Navigate to C:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\ucrt (Note that you don’t drill down into the sys folder)

Click Select Folder > Ok > Ok

Once I did that the error was gone along with related errors in the code.

What is the Windows equivalent to the capabilities defined in sys/select.h and termios.h

I have an application in linux, which is compiled successfully. I want to run the same program in windows.

But compilation produces the following errors related to header files.

  1. Cannot find sys/select.h
  2. Cannot find termios.h

How can I fix this?

2 Answers 2

The Windows API is structurally and stylistically very different from the blend of system calls and library routines provided by any flavor of Unix.

termio.h

Windows does terminal I/O with a very different model from any *nix system. As a result, there really is no direct equivalent to the termios.h header and its friends.

You want to read at MSDN about the Windows Communications Resources.

Some things to learn more about include:

In general, you will find that you need to deal a lot more with the Windows API directly because stdio will add to the confusion when doing device I/O.

select.h

There isn’t a direct equivalent to the Unix select(2) system call.

In Windows, many kernel objects can be in either a signaled or non-signaled state, and the act of signalling the object can be used to release a thread that called WaitForMultipleObjects() . Some but not all HANDLE objects are signaled when data is available. Specifically, I know that HANDLE s from WinSock have that capability, but I don’t know about the Comm API. I know that HANDLE s to an open file do not.

If you need to wait for an event in a thread that is processing window messages, then you should probably use MsgWaitForMultipleObjects() instead, since it will properly deliver messages while the thread is otherwise blocked.

Read about the Windows synchronization primitives at the MSDN article Using Synchronization.

Читайте также:  Mac os finder webdav

However, there are several kinds of asynchronous I/O built into Windows that can replace the need for select() by a change of design. Both will require extensive use of features that cannot be used in combination with the C stdio library.

MSDN has several articles on I/O techniques, as well as numerous examples:

Note that much of the information on how Windows works is scattered among the overview articles and the remarks sections of the reference material for the API functions and structures. This can give the impression that nothing is completely documented on a first reading.

Porting with Cygwin

Another approach is to use Cygwin to do the port. It provides most of a POSIX layer over the Windows API. However, you will end up with an application that is dependent on the Cygwin DLL which is GPL unless you purchase a commercial use license from them. It can be tricky to use Cygwin to get an application that works well for a Windows user with no Unix experience also, since so many other assumptions about the way the two systems are setup and used differ.

Cygwin has done a fair amount of heavy lifting to build an implementation of select() that works on Windows given a mix of different open file descriptors. This effort is described in the User’s Guide.

Do be aware that building against Cygwin is only documented and supported if done from within the Cygwin environment. It usually is not sufficient to just put Cygwin’s bin on the Windows PATH and work from a command prompt. You really need to launch Cygwin’s build of bash and compile from there so that everything is using the same Cygwin-style mount points and simulated Unix file structure.

Mixing Cygwin header files with third-party tool header files is a sure path to madness.

Edit: I’ve rearranged a bit, and added some material in response to comments.

Порт сокетных приложений из Unix в Windows

Как известно, концепция сокетов была разработана в Беркли, и затем реализована сначала в BSD, затем в Linux и, наконец, с некоторыми изменениями, и в Windows. Таким образом, это делает сетевое программирование на обеих платформах очень сильно похожим и перенос Unix приложения на Win-платформу становится не очень сложным делом.

Эта статья — попытка помочь тем, кто впервые решил осуществить порт сокетного приложения из Unix (Linux, BSD) в Windows. Зачем? Кто-то решает поднять свой уровень кодинга на новую высоту, кому-то это просто интересно, а кто-то ищет новые задачи для решения. Совет: не пытайтесь сразу портировать что-нибудь достаточно большое и сложное, начните с простых утилит вроде traceroute, nslookup и с прочтения этой статьи :-). Базовых знаний приемов сетевого программирования на C++ будет вполне достаточно. Все примеры из статьи компилировались на VC++ 6.0 под Win2k prof. и WinXP prof.

UNIX и Windows по разному обращаются с сокетами: в UNIX сокеты обрабатываются системой точно так же, как дескрипторы файлов integer типа, в то время как Windows это хэндл unsigned типа — SOCKET. В Unix все I/O действия выполняются чтением или записью в соответствующий дескриптор — число (integer) ассоциированное с открытым файлом, сетевым соединением, терминалом и т.п.

Читайте также:  Dvd ripper для mac os

В Unix коды ошибок доступны через переменную errno, в Windows нужно использовать функцию WSAGetLastError().

И в Unix и в Windows порт определяется параметром, переданном функции htons(), но в Windows некоторые, наиболее часто используемые порты предопределены в
winsock.h:

IPPORT_ECHO — 7
IPPORT_DISCARD — 9
IPPORT_SYSTAT — 11
IPPORT_DAYTIME — 13
IPPORT_NETSTAT — 15
IPPORT_FTP — 21
IPPORT_TELNET — 23
IPPORT_SMTP — 25
IPPORT_TIMESERVER — 37
IPPORT_NAMESERVER — 42
IPPORT_WHOIS — 43
IPPORT_MTP — 57

Заголовочные файлы
Вот список функций Unix и соответствующих им .h-файлов

socket()
[ #include ]
[ #include ]

bind()
[ #include ]
[ #include ]

connect()
[ #include ]
[ #include ]

listen()
[ #include ]
[ #include ]

Эти два файла к сокетам не относятся, но обычно присутствуют в Unix программах:

Т.е. типичное начало сетевой UNIX программы выглядит так:

#include
#include
#include
#include
#include

При переносе в Windows, все эти строки заменяются на одну:

Объявление winsock.h уже включено в windows.h.

Вторым шагом будет линковка приложению Wsock32.lib (Для VC++: меню Project->Settings, на вкладке Link, дописать wsock32.lib к списку библиотек).

UNIX и Windows имеют ряд общих, выполняющих одинаковые функций
процедур. Это большинство функций работы с TCP/UDP, все функции преобразования + используемые ими структуры. Это, например, функции htons() и inet_addr() и структуры sockaddr и sockaddr_in.

Вот список этих функций:
socket()
bind()
listen()
connect()
accept()
sendto()
recvfrom()
gethostname()

А вот список функций, делающих одно и то же, различающихся только названиями:

Unix Windows
close() closesocket()
ioctl() ioctlsocket()
read() recv()
write() send()

Дополнительно к вышесказанному, каждое сокетное приложение Windows должно содержать вызовы функций WSASStartup() и WSACleanup(), которые подготавливают к использованию Winsock и освобождают его, соответственно.

Для начала, перенесем что-нибудь простенькое. Например утилиту, определяющую IP-адрес хоста по его имени. Вот UNIX код:

#include
#include /* Этот файл нужен функции
gethostbyname() */
#include
#include
#include

int main(int argc, char *argv[])
<
struct hostent *he;

if ((he=gethostbyname(argv[1]))==NULL)
<
printf («gethostbyname() error\n»);
exit (-1);
>

printf («Hostname : %s\n»,he->h_name); /* Вывод имени хоста */
printf («IP Address: %s\n»,inet_ntoa(*((struct in_addr *)he->h_addr))); /* И его IP-адреса
*/
>

Попытка скомпилировать этот код без изменений была горячо воспринята VC++ — компилятор ругнулся на отсутствие .h файлов и сообщил, что компилировать программу он не собирается :-). Первым делом удаляем 2-5 строки, заменив их на:

и немного изменим строку 6:

void main(int argc, char **argv)

не забыв прилинковать wsock32.lib к проекту. Теперь программа компилируется без проблем, но при попытке ею воспользоваться выдает лаконичное: «gethostbyname() error». В чем дело? Все просто, не были вызваны WSAStartup() и WSACleanup()! Добавляем вызовы этих функций и код нормально компилируется.

Вот код портированного, работающего Win приложения:

void main(int argc, char **argv)
<
WSADATA wsdata;
WSAStartup(0x0101,&wsdata);
struct hostent *he;

if (argc! = 2)
<
printf(«Usage: %s hostname\n»,argv[0]);
>

if ((he = gethostbyname(argv[1])) == NULL)
<
printf(«gethostbyname() error\n»);
>

printf («Hostname : %s\n»,he->h_name);
printf(«IP Address: %s\n»,inet_ntoa(*((struct in_addr *)he->h_addr)));

Конечно, это — очень простое приложение. Попробуем перенести программу посложнее
— TCP streaming server.

#include
#include
#include
#include

#define PORT 3550 /* Порт, открываемый программой */
#define BACKLOG 2 /* Число соединений */

main()
<
int fd, fd2; /* дескрипторы */
struct sockaddr_in server; /* информация о сервере */
struct sockaddr_in client; /* информация о клиенте */
int sin_size;

Читайте также:  Linux порядок загрузки модулей

if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 )
< /* вызов socket() */
printf («socket() error\n»);
exit (-1);
>

server.sin_family = AF_INET;
server.sin_port = htons (PORT);
server.sin_addr.s_addr = INADDR_ANY;
bzero (&(server.sin_zero),8);

printf («You got a connection from %s\n», inet_ntoa(client.sin_addr) );
send (fd2,»Welcome to my server.\n»,22,0);
close (fd2);
>>

Итак, сначала повторим шаги из предыдущего примера — оставим объявления только windows.h и stdio.h и прилинкуем wsock32.lib. Попытка компиляции приносит две ошибки: одна — по поводу функции bzero(), вторая — по поводу функции
close() — компилятор сообщает, что она — invalid identifier :-). Первая ошибка лечится очень просто — удаляем всю 21-ю строку. Для исправления второй, смотрим в таблицу, приведенную выше и заменяем close() на ее Win-аналог — closesocket(). Добавляем вызовы WSAStartup() и WSACleanup() и voila — программа компилируется без проблем. После запуска программы видим пустую командную строку, все правильно — сервер ждет клиента :-).

Windows код сервера:

#include
#include
#define PORT 3550
#define BACKLOG 2

main()
<
WSADATA wsdata;
WSAStartup(0x0101,&wsdata);

struct sockaddr_in server;
struct sockaddr_in client;
int sin_size;

if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 )
<
printf(«socket() error\n»);
exit(-1);
>

server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = INADDR_ANY;

if (listen (fd,BACKLOG) == -1)
<
printf («listen() error\n»);
exit (-1);
>

while (1)
<
sin_size=sizeof (struct sockaddr_in);

printf («You got a connection from %s\n»,inet_ntoa(client.sin_addr) );
send (fd2,»Welcome to my server.\n»,22,0);
closesocket (fd2);

TCP streaming client

#include
#include
#include
#include
#include /* необходим для struct hostent */

#define PORT 3550 /* Порт, к которому будем коннектиться */
#define MAXDATASIZE 100 /* Макс. размер данных в байтах */

int main (int argc, char *argv[])
<
int fd, numbytes; /* дескрипторы */
char buf[MAXDATASIZE]; /* здесь будем хранить полученный текст */

struct hostent *he;
struct sockaddr_in server;

if ((he=gethostbyname(argv[1]))==NULL)
<
printf(«gethostbyname() error\n»);
exit(-1);
>

if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1)
<
printf(«socket() error\n»);
exit(-1);
>

server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr = *((struct in_addr *)he->h_addr);
bzero(&(server.sin_zero),8);

if ((numbytes=recv(fd,buf,MAXDATASIZE,0)) == -1)
<
printf(«recv() error\n»);
exit(-1);
>
buf[numbytes]=’\0′;
printf(«Server Message: %s\n»,buf);
close(fd);
>

И, без лишних слов, Windows код — для его получения нужно проделать те же, вышеописанные, шаги.

#define PORT 3550
#define MAXDATASIZE 100

int main(int argc, char *argv[])
<
WSADATA wsdata;
WSAStartup(0x0101,&wsdata);
int fd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in server;

if ((he=gethostbyname(argv[1])) == NULL)
<
printf(«gethostbyname() error\n»);
exit(-1);
>

if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1)
<
printf(«socket() error\n»);
exit(-1);
>

server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr = *((struct in_addr *)he->h_addr);

if ((numbytes=recv(fd,buf,MAXDATASIZE,0)) == -1)
<
printf(«recv() error\n»);
exit(-1);
>

buf[numbytes] = ‘\0’;
printf(«Server Message: %s\n»,buf);
closesocket(fd);
WSACleanup();
return -1;
>

Запустив клиента (при запущенном сервере, естественно) с аргументом localhost (что-то вроде tcp_client.exe localhost) видим приветствие сервера — «Welcome to my server». С чем я тебя и поздравляю
:-).

Вот те шаги, которые нужно делать в первую очередь, при переносе приложений:

1. Заменить объявления заголовочных файлов UNIX на windows.h и прилинковать wsock32.lib
2. Добавить вызовы функций WSAStartup() и WSACleanup()
3. Заменить функции вроде close() и ioctl() на их Windows-аналоги

Можно даже написать небольшую программу делающую это автоматически (например на Perl). Она здорово облегчит процесс порта приложений.

Все примеры из статьи (exe + исходники) можно скачать
здесь.

Оцените статью