Fatal error conio h нет такого файла или каталога

I want to execute a .cpp file while contains the #include header file, but while executing I'm getting the following error: "program.cpp:4:20: fatal error: conio.h: No such file or

TL;DR

You basically have 2 choices on how to proceed. You can either install a package that includes conio.h + its library as I describe below or you can use ncurses.h + its library and swap out and/or remove function calls that depend on it as @Ashish Kulkarni describes in his answer. Either option is viable and is up to the developer/implementer to decide which is the «correct» path.


The conio.h header + library for C/C++ is not something you’ll typically find as being installed by default with most Linux distros. At least not the ones that I’m familiar with Fedora/CentOS/RHEL/Debian/Ubuntu.

NOTE:: Also the use of ncurses.h is not appropriate here either, since that library will likely not include any of the functions that you’re looking for (clrscr(), getch(), etc.) since your .cpp file would seem to be coming from a Windows environment originally.

However you have the option with Linux to install packages from centrally managed repositories. Looking for a package that includes conio.h on my Fedora system I turned up this package. I realize you’re on Ubuntu but on Fedora the package is called libconio that provides exactly the libraries that you’re looking for.

$ yum info libconio.i686
Loaded plugins: auto-update-debuginfo, changelog, langpacks, refresh-packagekit
Available Packages
Name        : libconio
Arch        : i686
Version     : 1.0.0
Release     : 3.2
Size        : 6.3 k
Repo        : rpm-sphere
Summary     : Implementation of conio.h functions
License     : GPL
Description : libconio is an implementation of conio.h functions that some 
            : DOS and Windows compilers provide. It's purpose is to allow 
            : developers to use functions like getch, getche, textcolor and 
            : others in a linux environment.

Looking on a Ubuntu system I have there’s a similar package called elks-libc that also contains conio.h.

$ apt-cache show elks-libc
Package: elks-libc
Priority: optional
Section: devel
Installed-Size: 651
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Juan Cespedes <cespedes@debian.org>
Architecture: all
Source: linux86
Version: 0.16.17-3.1ubuntu3
Replaces: bcc (<< 0.14.9), linux86
Recommends: bcc (= 0.16.17-3.1ubuntu3)
Conflicts: linux86
Filename: pool/main/l/linux86/elks-libc_0.16.17-3.1ubuntu3_all.deb
Size: 214574
MD5sum: 75d87d8c2c906579ec84624fff93d76d
SHA1: 5cd6d3b9c5a881ad5fcdcffbd5a075761b017731
SHA256: 57bee73becbeae5dc2bc4cd859c13dc065e4a49472d876225e3e37fd6538feb2
Description-en: 16-bit x86 C library and include files
 This is the C library used to compile with bcc. It includes all the
 headers and static libraries needed to build 16-bit applications,
 for Linux/8086, Linux/i386 and DOS .COM executables.
Description-md5: 2da04d6881989db1f4a11df4a992c06f
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Origin: Ubuntu
Supported: 18m

And here’s the file:

$ apt-file list elks-libc | grep conio.h
elks-libc: /usr/lib/bcc/include/conio.h

So you can simply install this package to get the header file + libraries that your application requires to compile.

$ sudo apt-get install elks-libc

NOTE: You may need to adjust your include path to gcc to pick this header file up.

elks-libc is only for 8088 Intel processors

As mentioned in the comments, elks-libc is intended for use on system’s that are targeting the Intel 8088 CPU. You can instead download libconio.h from the SourceForge project titled: Linux c++ implementation of conio.h. You’ll have to install it manually but it shouldn’t be too difficult to do this.

Simple Linux implementation of Borland’s conio (conio.h) library. It uses Ncurses. It includes most functions required to write a basic application using conioh (i.e. getch(), cprintf(), puts() and more).

You can also get the entire libconio project’s source from this SourceForge project titled: libconio and unpack it.

Details on doing this as well as building it and compiling it are covered in this tutorial titled: How to use with GCC.

artyom5613

0 / 0 / 0

Регистрация: 04.02.2017

Сообщений: 3

1

29.10.2017, 11:34. Показов 10510. Ответов 6

Метки нет (Все метки)


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
 
#include <conio.h>  // Упр3.cpp:3:19: fatal error: conio.h: Нет такого файла или каталога
 
using namespace std;
int main()
{
    char ch ;
   unsigned long total= 0;
    
  
    cout << "Введите число";
 
  while((ch=getche()) != 'r'){
      total = (total*10) + (ch-48);
      cout <<"nВы ввели: " << total << endl;
     
  }
 
}

Это пример из книжки, и не работает, сижу на Ubuntu в Visual Studio Code, в gcc такая же ошибка.

Потом я скачал conio.h(кастом вроде) запихнул в папку с файлом поменял <> на «» и теперь такая ошибка: conio.h:52:21: fatal error: ncurses.h: Нет такого файла или каталога

Я как понимаю это из-за Ubuntu, только вот переходить на лагающий Windows не хочется.
Поскажите как быть? Учусь по книжке и использовать иные от книги функции не хочется.
Пробовал различные IDE

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Заклинатель змей

611 / 508 / 213

Регистрация: 30.04.2016

Сообщений: 2,412

29.10.2017, 11:46

2

artyom5613, потому что эти библиотека из прошлого века под MS-DOS. Хотите работать с ним — поставьте себе DOS box и BorlandC



0



0 / 0 / 0

Регистрация: 04.02.2017

Сообщений: 3

29.10.2017, 12:02

 [ТС]

3

Добавлено через 1 минуту

Цитата
Сообщение от DobroAlex
Посмотреть сообщение

artyom5613, потому что эти библиотека из прошлого века под MS-DOS. Хотите работать с ним — поставьте себе DOS box и BorlandC

DobroAlex,Книга 2017 года, подробно описано как работать с visual c++, и подразумевается , что conio.h должна работать
А есть альтернатива?



0



Заклинатель змей

611 / 508 / 213

Регистрация: 30.04.2016

Сообщений: 2,412

29.10.2017, 12:43

4

artyom5613, или поставьте Окна и MVS, или Dos



0



pav1uxa

1943 / 1768 / 825

Регистрация: 23.01.2014

Сообщений: 6,230

29.10.2017, 13:22

5

artyom5613,

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
 
using namespace std;
int main()
{
    char ch ;
    unsigned long total= 0;
 
    cout << "Введите число";
 
    while(cin >> ch && ch != 'r'){
        total = (total*10) + (ch-48);
        cout <<"nВы ввели: " << total << endl;
    }
}



0



119 / 9 / 2

Регистрация: 06.09.2017

Сообщений: 82

29.10.2017, 16:59

6

Цитата
Сообщение от artyom5613
Посмотреть сообщение

Поскажите как быть?

Код

apt-get install libncurses{,w}5-dev

Код

g++ -I. $(pkg-config --cflags ncursesw) main.cpp $(pkg-config --libs ncursesw)

Только работать будет криво.



0



Форумчанин

Эксперт CЭксперт С++

8193 / 5043 / 1437

Регистрация: 29.11.2010

Сообщений: 13,453

30.10.2017, 14:22

7

artyom5613, conio.h не входит в стандарт и является досовским заголовочным файлом.
Есть порт на Linux, но лучше просто избавиться от кода, который от него зависит. Или переписать на средства API ОС, если стандартные функции не подходят.



0



  • Печать

Страницы: [1] 2  Все   Вниз

Тема: компилятор не находит заголовочный файл conio.h  (Прочитано 7729 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн
tro9an

вот код

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
char dir='a';
int x=10,y=10;
cout << "Нажмите Enter для выхода...n";
while (dir!='r')
{
cout << "nВведите ваши координаты: " << x << ", " << y;
cout << "Выбирете направление (n,s,e,w): ";
dir=getche();
if (dir=='n')
y--;
else
if (dir=='s')
y++;
else
if (dir=='e')
x++;
else
if (dir=='w')
x--;
}
return 0;
}

myproga.cpp:3:19: error: conio.h: Нет такого файла или каталога
myproga.cpp: In function ‘int main()’:
myproga.cpp:13: error: ‘getche’ was not declared in this scope

как это исправить?


Оффлайн
arrecck


Оффлайн
tro9an

ну вместо getche() написал getchar()

myproga.cpp:12: error: ‘getchar’ was not declared in this scopeчё теперь делать?
насчёт сылки на вику, с++ я только начинаю познавать, там слишком сложна описано


Оффлайн
Not eXist

Ну не является библиотека conio стандартной библиотекой C++.


Оффлайн
VestniK

ну вместо getche() написал getchar()
myproga.cpp:12: error: ‘getchar’ was not declared in this scopeчё теперь делать?
насчёт сылки на вику, с++ я только начинаю познавать, там слишком сложна описано

Можно подробней где там слишком сложно написано????

Тем не менее, он не является частью языка программирования Си, стандартной библиотеки языка Си, ISO C или требуемой стандартом POSIX.

Большинство компиляторов языка Си, предназначенных для UNIX и Linux, не имеют этого файла и не обеспечивают сопутствующих библиотечных функций.

Что именно тут непонятно?


Оффлайн
tro9an

ну точто он не является я уже понял, так какой функцией  заменить функцию getche() и вообше чё с ней делать если нужна именно она?

вот строка
Члены-функции
после этой строки идёт столбец вот там ппц…


Оффлайн
VestniK

Искать в гугле по ключивым словам C getchar Linux. Есть примеры как реализовать эту функцию через ncurses или через UNIX’овые функции работы с терминалом. Помоему даже на жтом форуме были листинги готовых решений. Поиск рулит.


Оффлайн
Not eXist

ЕМНИП, getch есть в библиотеке ncurses.


Оффлайн
VestniK

вот строка
Члены-функции
после этой строки идёт столбец вот там ппц…

После этой строчки идёт не пипец, а перечисление функций библиотеки conio. Готовся к тому, что это будет в программировании часто встречаться


Оффлайн
arrecck

ТС, читать умеешь?
Начал изучать программирование, привыкай, что гуглить придется много и часто
Книжку по с++ для linux скачай, там будет все компилироваться


Оффлайн
Yurror


Оффлайн
ierofant

Что вы всех людей в гугл отсылаете? По вашему этот сайт был создал как посредник для Google ?
А по вопросу: conio.h это древний заголовочник, был в MS-DOS’е, он не является частью C.  Для линукса надо искать иную альтернативу.
Почему бы std::cin не использовать для этих целей?

« Последнее редактирование: 26 Октября 2010, 11:17:07 от ierofant »


Оффлайн
VestniK

Что вы всех людей в гугл отсылаете? По вашему этот сайт был создал как посредник для Google?

Потому что надоедает видеть как раз в месяц кто-то, не удосужившись даже потратить 5 минут на поиск, задаёт вопрос который уже обсуждался миллион раз и как мининум 2-3 разных ответа на него можно найти даже на этом форуме не говоря уж о гугле.

Опять же, если человек не научится самостоятельно искать ответы на свои вопросы, то в программировании ему делать нечего. Так что если он самостоятельно найдёт ответ на этот вопрос, то пользы от этого, для него же самого, будет несоизмеримо больше нежели если он тупо получит разжёваный ответ с листингами и примерами здесь.


Оффлайн
ierofant

Что вы всех людей в гугл отсылаете? По вашему этот сайт был создал как посредник для Google?

Потому что надоедает видеть как раз в месяц кто-то, не удосужившись даже потратить 5 минут на поиск, задаёт вопрос который уже обсуждался миллион раз и как мининум 2-3 разных ответа на него можно найти даже на этом форуме не говоря уж о гугле.

Опять же, если человек не научится самостоятельно искать ответы на свои вопросы, то в программировании ему делать нечего. Так что если он самостоятельно найдёт ответ на этот вопрос, то пользы от этого, для него же самого, будет несоизмеримо больше нежели если он тупо получит разжёваный ответ с листингами и примерами здесь.

Давайте создадим мегапост «Ищите в гугл» навроде поста «Makefile: как скомпилировать свой первый Hello World». Ибо честное слово, все эти отсылки туда раздражают не меньше чем сами вопросы.


Оффлайн
VestniK

Процетирую самого себя:

Опять же, если человек не научится самостоятельно искать ответы на свои вопросы, то в программировании ему делать нечего. Так что если он самостоятельно найдёт ответ на этот вопрос, то пользы от этого, для него же самого, будет несоизмеримо больше нежели если он тупо получит разжёваный ответ с листингами и примерами здесь.

так что отсылки в гугл меня ни капли не раздражают. Я сам не задаю вопрос пока хотя бы часик не поисследовав вопрос самостоятельно. Поэтому вопросов, как правило, не задаю ибо на все мыслемые вопросы ответы уже там есть.

Давайте создадим мегапост «Ищите в гугл» навроде поста «Makefile: как скомпилировать свой первый Hello World».

уже есть: http://maddog.sitengine.ru/smart-question-ru.html

« Последнее редактирование: 26 Октября 2010, 15:41:04 от VestniK »


  • Печать

Страницы: [1] 2  Все   Вверх

i am a beginner in ubuntu os.
In the terminal box, i try to run a simple C programing code using Visual Studio, and it shows me ***

fatal error: conio.h: No such file or directory


that kind of error.
So, what should i do to resolve this error ?

schaiba's user avatar

schaiba

7,3701 gold badge33 silver badges31 bronze badges

asked Jan 5, 2020 at 6:14

suvasish das's user avatar

This header file is from old MS-DOS dev interface. You can replace it (almost) with curses.h. For more details you can check this answer.

conio.h is a C header file used in old MS-DOS compilers to create text
user interfaces. Compilers that targeted non-DOS operating systems,
such as Linux, Win32 and OS/2, provided different implementations of
these functions.

The #include <curses.h> will give you almost all the functionalities
that was provided in conio.h

nucurses need to be installed at the first place

In deb based Distros use

sudo apt-get install libncurses5-dev libncursesw5-dev

answered Jan 5, 2020 at 7:34

Romeo Ninov's user avatar

Romeo NinovRomeo Ninov

15.3k5 gold badges31 silver badges41 bronze badges

2

What you do is should stop trying to write MS/PC-DOS programs. You are using a completely different operating system.

conio.h is one of the headers that comprises the C language bindings to the DOS API. Programs that employ it are MS/PC-DOS programs.

People will tell you that curses «does the same thing». It actually really does not, as the DOS console API has quite a different paradigm to full-screen TUIs built on POSIX terminal I/O. Porting from one to the other is not as simple as a header file change. (There were compatibility headers in compilers for OS/2 and Windows NT, because those operating systems have «console» I/O paradigms that map far better to the DOS console API.) And that’s not yet accounting for the fact that there were two flavours of console API as employed in old DOS code, Borland/Watcom and Microsoft.

The right change is to simply forget about the DOS API from 30 years ago, and write a program that uses your actual operating system’s APIs: POSIX terminal I/O with your choice of TUI library, X11 with your choice of toolkit, or whatever.

Further reading

  • Jonathan de Boyne Pollard (2010). The gen on the C and C++ language bindings to the DOS API. Frequently Given Answers.
  • https://unix.stackexchange.com/a/558840/5132

answered Jan 5, 2020 at 15:42

JdeBP's user avatar

JdeBPJdeBP

64.7k12 gold badges155 silver badges332 bronze badges

1

i am a beginner in ubuntu os.
In the terminal box, i try to run a simple C programing code using Visual Studio, and it shows me ***

fatal error: conio.h: No such file or directory


that kind of error.
So, what should i do to resolve this error ?

schaiba's user avatar

schaiba

7,3701 gold badge33 silver badges31 bronze badges

asked Jan 5, 2020 at 6:14

suvasish das's user avatar

This header file is from old MS-DOS dev interface. You can replace it (almost) with curses.h. For more details you can check this answer.

conio.h is a C header file used in old MS-DOS compilers to create text
user interfaces. Compilers that targeted non-DOS operating systems,
such as Linux, Win32 and OS/2, provided different implementations of
these functions.

The #include <curses.h> will give you almost all the functionalities
that was provided in conio.h

nucurses need to be installed at the first place

In deb based Distros use

sudo apt-get install libncurses5-dev libncursesw5-dev

answered Jan 5, 2020 at 7:34

Romeo Ninov's user avatar

Romeo NinovRomeo Ninov

15.3k5 gold badges31 silver badges41 bronze badges

2

What you do is should stop trying to write MS/PC-DOS programs. You are using a completely different operating system.

conio.h is one of the headers that comprises the C language bindings to the DOS API. Programs that employ it are MS/PC-DOS programs.

People will tell you that curses «does the same thing». It actually really does not, as the DOS console API has quite a different paradigm to full-screen TUIs built on POSIX terminal I/O. Porting from one to the other is not as simple as a header file change. (There were compatibility headers in compilers for OS/2 and Windows NT, because those operating systems have «console» I/O paradigms that map far better to the DOS console API.) And that’s not yet accounting for the fact that there were two flavours of console API as employed in old DOS code, Borland/Watcom and Microsoft.

The right change is to simply forget about the DOS API from 30 years ago, and write a program that uses your actual operating system’s APIs: POSIX terminal I/O with your choice of TUI library, X11 with your choice of toolkit, or whatever.

Further reading

  • Jonathan de Boyne Pollard (2010). The gen on the C and C++ language bindings to the DOS API. Frequently Given Answers.
  • https://unix.stackexchange.com/a/558840/5132

answered Jan 5, 2020 at 15:42

JdeBP's user avatar

JdeBPJdeBP

64.7k12 gold badges155 silver badges332 bronze badges

1

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error conio h file not found
  • Fatal error concurrent map writes
  • Fatal error compiling java lang exceptionininitializererror com sun tools javac code typetags
  • Fatal error compiling invalid target release 11 maven
  • Fatal error code a9a4c41c000005af mess failed to memory allocate danganronpa v3

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии