Porting a C program with unicode characters to Windows [duplicate] - c

I'm building a lightweight version of the ncurses library. So far, it works pretty well with VT100-compatible terminals, but win32 console fails to recognise the \033 code as the beginning of an escape sequence:
# include <stdio.h>
# include "term.h"
int main(void) {
puts(BOLD COLOR(FG, RED) "Bold text" NOT_BOLD " is cool!" CLEAR);
return 0;
}
What needs to be done on the C code level, in order that the ANSI.SYS driver is loaded and the ANSI/VT100 escape sequences recognized?

[UPDATE] For latest Windows 10 please read useful contribution by #brainslugs83, just below in the comments to this answer.
While for versions before Windows 10 Anniversary Update:
ANSI.SYS has a restriction that it can run only in the context of the MS-DOS sub-system under Windows 95-Vista.
Microsoft KB101875 explains how to enable ANSI.SYS in a command window, but it does not apply to Windows NT. According to the article: we all love colors, modern versions of Windows do not have this nice ANSI support.
Instead, Microsoft created a lot of functions, but this is far from your need to operate ANSI/VT100 escape sequence.
For a more detailed explanation, see the Wikipedia article:
ANSI.SYS also works in NT-derived systems for 16-bit legacy programs executing under the NTVDM.
The Win32 console does not natively support ANSI escape sequences at all. Software such as Ansicon can however act as a wrapper around the standard Win32 console and add support for ANSI escape sequences.
So I think ANSICON by Jason Hood is your solution. It is written in C, supports 32-bit and 64-bit versions of Windows, and the source is available.
Also I found some other similar question or post which ultimately have been answered to use ANSICON:
How to load ANSI escape codes or get coloured file listing in WinXP cmd shell?
how to use ansi.sys in windows 7
How can I get cmd.exe to display ANSI color escape sequences?
ansi color in windows shells
enable ansi colors in windows command prompt

Starting from Windows 10 TH2 (v1511), conhost.exe and cmd.exe support ANSI and VT100 Escape Sequences out of the box (although they have to be enabled).
See my answer over at superuser for more details.

Base on #BrainSlugs83 you can activate on the current Windows 10 version via register, with this command line:
REG ADD HKCU\CONSOLE /f /v VirtualTerminalLevel /t REG_DWORD /d 1

For Python 2.7 the following script works for me fine with Windows 10 (v1607)
import os
print '\033[35m'+'color-test'+'\033[39m'+" test end"
os.system('') #enable VT100 Escape Sequence for WINDOWS 10 Ver. 1607
print '\033[35m'+'color-test'+'\033[39m'+" test end"
Result should be:
[35mcolor-test[39m test end
color-test test end

Starting from Windows 10, you can use ENABLE_VIRTUAL_TERMINAL_PROCESSING to enable ANSI escape sequences:
https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx

If ANSICON is not acceptable since it requires you to install something on the system, a more lightweight solution that parses and translates the ANSI codes into the relevant Win32 API console functions such as SetConsoleTextAttribute.
https://github.com/mattn/ansicolor-w32.c

For coloring the cmd you need Windows.h and use SetConsoleTextAttribute() more details can be found in http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047%28v=vs.85%29.aspx

In lastest win10, it can be done by SetConsoleMode(originMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING). See https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#example

Maybe ANSICON can help u
Just download and extract files, depending on your windows os: 32bit or 64bit
Install it with: ansicon -i

I personally like clink. It not only processes ANSI codes, it also adds many other features so Windows Console behaves like bash (history, reverse history search, keyboard shortcuts, etc.):
The same line editing as Bash (from GNU's Readline library).
History persistence between sessions.
Context sensitive completion;
Executables (and aliases).
Directory commands.
Environment variables
Thirdparty tools; Git, Mercurial, SVN, Go, and P4.
New keyboard shortcuts;
Paste from clipboard (Ctrl-V).
Incremental history search (Ctrl-R/Ctrl-S).
Powerful completion (TAB).
Undo (Ctrl-Z).
Automatic "cd .." (Ctrl-PgUp).
Environment variable expansion (Ctrl-Alt-E).
(press Alt-H for many more...)
Scriptable completion with Lua.
Coloured and scriptable prompt.
Auto-answering of the "Terminate batch job?" prompt.

Ansi.sys (in the system32 folder) is an "MSDOS driver" provided as part of Windows XP, 2000, and earlier versions of NT. In 2000 and XP, it is located in the system32 folder (I don't remember the structure of earlier versions of NT). Programs that run in the DOS subsystem and use standard output can use ANSI.SYS just as they could running over MSDOS.
To load ansi.sys, you must use the device= or devicehigh= command in config, just as you would in MSDOS. On Windows NT 5 (2K & XP), each copy of the DOS subsystem can be given a separate config file in the pif/shortcut (use the "advanced" button), and there is a default file called CONFIG.NT (also in the system32 folder), which is used if the pif/shortcut does not specify a special config file.
When ansi.sys is loaded correctly, mem /d will report that it is loaded. On earlier versions of NT, you can and must load a proper DOS environment to load ansi.sys, and ansi art will work at the prompt. On Win 2K and XP, loading ansi.sys will have no effect on your "CMD prompt" because CMD is not a DOS program: it is a 32 bit Windows console program. For some reason that I do not understand, on WinXP, even if you load a fixed copy of command.com using "command.com /p", the command prompt will not be ansi enabled: perhaps when you do it that way it only emulates loading command.com?
In any case, when you use an actual DOS version of command.com, ansi is enabled after being loaded: you can demonstrate it's use with a bit of ansi art like this:
command /c type ansiart.ans
(here is an example: http://artscene.textfiles.com/ansi/artwork/beastie.ans)
CONFIG.NT (in the system32 folder) contains an example of the syntax for loading device drivers. You will need to be an Administrator to edit that default file, or you can make a copy of it.
On Win 2K and XP, the default "shortcut" for MSDOS is a .PIF file, not a .LNK file. If you create a .lnk file to CMD, you won't be able to set special config and autoexec files, it will use the default CONFIG.NT. If you want to use a special config file for just one DOS application, you can make a copy of the "MSDOS shortcut", or you can make a copy of "_default.pif", found in your Windows folder.

Had the same issue. I installed ConEmu and that one solved my problem.

I found this tool to be working for my end.
Microsoft Color Tool from GitHub
Unzip the compressed file then open CMD with Administration permission.
Go to the folder where you unzip the file in CMD.
Then execute this command "colortool -b scheme-name"
The scheme-name needs to be replaced with any of these options below:
campbell.ini
campbell-legacy.ini
cmd-legacy.ini
deuternopia.itermcolors
OneHalfDark.itermcolors
OneHalfLight.itermcolors
solarized_dark.itermcolors
solarized_light.itermcolors
In my case, the command would be like this "colortool -b solarized_dark.itermcolors"
Click right on the console window and select Properties.
You don't need to change any value just click "OK" to save the setting. (You will notice that your font already contains colors).
Console Property
Then restart your cmd or powerShell.
The ANSI color should be enabled and working with the color scheme you chose before.

Somehow in Windows you just need to call any shell command first, rather call the system function. Just in start of your main method put system("");, and don't forget to include stdlib.h.
I noticed this when I looked at some of my old programs that also used ANSI codes to understand why they work, but my new code is not

Related

How to synchronize code files on windows with WSL/linux?

Basically I have some C/C++ code that I need to build and debug on a Linux machine. Unfortunately, my windows laptop doesn't have enough free hard space to install some Linux dist nor does it have enough free RAM to comfortably run VM.
Until now, I dealt with it rather comfortably using WSL, but the scale was rather small. It was easy to edit and debug 2-3 .c files through CLI and gdb, but it became really annoying on a large scale projects.
I want something simple as "edit code in windows IDE [X], compile it on remote Linux/WSL (the project uses Makefiles), and preferably debug it via gdb".
VS has something close to what I want, but it can't deal with existing Linux projects. It needs to create a new configuration which is alien to the project's Makefile.
I know this question is a bit old, but I think the solution is to make a symlink between your WSL folder and the Window's folder. This is how I handled it for a Ubuntu-20.04 WSL:
Access PowerShell in Administrator mode
Type cmd.exe in the PowerShell
Once cmd.exe is opened, type mklink /d C:\<path_to_your_Windows_folder> \\wsl$\Ubuntu-20.04\home\<your_user>\<path_to_your_WSL_folder>
EDIT
This was tested under Windows 10 Version 2004 with WSL2
I'm unsure about C and C++ but it sounds like this is exactly the same as how i work in node and javascript every day.
I checkout my code using git inside WSL to a location like /mnt/c/code/myproject. Then using sublime/VS code/webstorm i edit the files in windows in the location c:\code\myproject this works really well and have been doing this every day for over a year.
Things to be aware of are that you need to ensure that your editor of choice saves files with linux line endings and that all command line operations are done inside WSL.
Please see this article to see the differences between windows and linux files and how this works inside the WSL.
I want something simple as "edit code in windows IDE , compile it on remote linux/WSL
You will have something as simple as that.
Only with Windows 19.03 though:
See "Updated WSL in Windows 10 version 1903 lets you access Linux files from Windows"
Microsoft's Craig Loewen says:
In the past, creating and changing Linux files from Windows resulted in losing files or corrupting data. Making this possible has been a highly requested and long anticipated feature. We're proud to announce you can now easily access all the files in your Linux distros from Windows.
So how does this work? He goes on to explain:
To put it briefly: a 9P protocol file server facilitates file related requests, with Windows acting as the client.
We've modified the WSL init daemon to include a 9P server. This server contains protocols that support Linux metadata, including permissions.
There is a Windows service and driver that acts as the client and talks to the 9P server (which is running inside of a WSL instance).
Client and server communicate over AF_UNIX sockets, since WSL allows interop between a Windows application and a Linux application using AF_UNIX as described in this post.
Warning:
The old rules still apply, you should NOT access your Linux files inside of the AppData folder!
If you try to access your Linux files through your AppData folder, you are bypassing using the 9P server, which means that you will not have access to your Linux files, and you could possibly corrupt your Linux distro.

What's the difference between MS-DOS and Batch?

I read that apparently MS-DOS and Batch are NOT the same thing, but that's how I've been taught.
I couldn't find sites or a Q&A on it so can anyone help shed some light?
Batch file language is part of MSDos. It has also been part of MSDos successors - OS/2, Windows 16 bit, Win 32 on 9x as a MSDos 7, and on Win NT 32 bit as MSdos 5.5 which is the current one. 64 bit doesn't have MSDos.
In OS/2 IBM engineers tried bolting programming language constructs on to MSDos batch - Microsoft engineers updated this for Windows 2000. To remain compatible with MSDos batch this requires horrible hacks. The two command processors are
command.com - 16 bit MSDos command processor. There are many versions 1,2, 3, 3.3, 4, 5, 6, 6.22, (on 9x) 7, 7.1, (on Win NT) 5.5.
cmd.exe - 32 bit or 64 bit windows command processor that understands MSDos syntax as well. There are two main versions - NT4 and OS/2 and Windows 2000 and later.
In Windows if you type in command.com it sends your command to cmd.exe to be executed.
Try this.
Type in Start - Run
cmd
then in the console window
ver
Then type in Start - Run
command
then in the console window
ver
Then type in Start - Run
command /k ver
ALSO
Just because a program is a console program does not imply that either command processor is involved. It you type ftp in Start - Run only ftp.exe is running in that console.
MS Dos is the Microsoft Disk Operating System nowadays just reffered to as an OS. Windows has now become a part of the Microsoft OS and is a graphical layer allowing much more operability to the end user but we still have access to many DOS based commands.
This is done through the Command Prompt (CMD.EXE).
The Command prompt allows a terminal style (none graphical) environment where we can put together commands to interact with the machine. For example, DIR will give a directory listing for the current directory. These commands can be manipulated with parameters being passed in for example DIR /AD /S will use AD to list all Directories (not files) and /S will recurse through subdirectories.
If you spend any time working in a DOS environment there are many commands you would want to string together, You can create a text file with a .bat extension to allow this, running this "Batch" file will run the commands sequentially one after the other. It is exactly as the name implies, a Batch of commands for it to perform.
The Batch file DOES allow for some basic loops and a GoTo style jump. A perfect example of a Batch file in it's basic form was Autoexec.bat. This was used as your computer booted to fire off commands to load drivers for audio cards / graphics cards / network cards etc.
I STILL use the Command prompt very often, I find it easier to create a batch file from a bunch of formulas in Excel for 1 off repetitive commands and I can do this quicker than I probably could if I were to build a VBA solution to interact with the files.

When was Batch created?

I know this isn't strictly a programming related question, but I cannot seem to find an answer.
In what year was Batch created? Or is it more appropriate to talk about the year CMD was created? In which case - in what year was CMD created?
I apologize if this question is against the rules in any way. The reason I ask is to participate in a challenge over at the Code Golf StackExchange site.
Do you need to distinguish the command.com and cmd.exe ?
Command.com - was the command line interpreter from the earliest versions of DOS and QDOS created by Tim Paterson (around 1981) , but the command.com also passed through a lot of changes and may be the most drastic in its 5th version.
MSDOS 1.0 supported commands - (CD COPY DEL DIR EDIT FORMAT HELP MKDIR RD REN TYPE )
In MSDOS 5.0 (1991) more advanced commands were introduced - (even microsoft keeps a documentation for it) and may be its a little bit closer to a programing language.
In 1993 Windows NT was released packed with the new cmd.exe (along with the old command.com) created by Therese Stowell - it has a lot new features like additional switches for FOR and IF commands , subroutines and etc. And this is the 'modern' batch-scripting what we know today (though it is close to the ms-dos 5 command.com).
This has cost me some time in googling but hope the info is enough :)
The earliest reference to batch files is 1981, with the release of IBM PC DOS 1.0 - it used the file AUTOEXEC.BAT to run various commands at startup.
And imo this question falls into a grey area regarding whether or not it's on-topic; there's no specific programming question, but it's still related to programming, and that's apparently okay according to the review audit that I recently failed.
MSDos was based on CP/M features for compatability. Unix type features added in in Ver 2. CMD started as a command shell that would run MSDos batch files but have added features in OS/2 (IBM not MS did CMD). CMD got taken into NT and there are two main versions pre Win 2000 and post Win 2000. Prior to Windows 2000 Dos batch files and programs ran in the OS/2 sub system, not the Dos emulator in the Windows sub system.
The command.com in Windows now is ver 5.5 and passes all commands to cmd to execute unless started like this command.com /k ver (compare that to typing command.com then ver).
I don't remember exactly when I bought my first PC computer, but it should be around 1984 or 1985; it was a "PC clone" Printaform computer that featured MS-DOS 2.11 with Batch files executed by command.com program. I vividly remember that the Batch features of that time were enough to write many interesting programs. It had variable management via SET command and %variable% value replacement, and FOR, IF and CALL commands, including recursive subroutines.
Shortly after that I read an article in Dr. Dobb's Journal that show me how to modify command.com's environment variables from a running program, so I wrote my first program of this type, LET.COM, that allowed me to perform advanced variable management in Batch files, like arithmetic operations, data input, etc. many years before the modern cmd.exe Batch file features.
You may review the history of MS-DOS development, including Batch file features, in many sites in the web, like this one in Wikipedia.

Control cmd prompt using C

I'm trying to write a C program to control the windows cmd prompt. For example, opening the cmd prompt, go to a specific directory (ex: C:/Program Files/...), and then run an exe in that folder.
Can this be done with C programming? If so, how? So far, I am only aware of system("cmd.exe") to open up the cmd prompt. How would I further interact with cmd prompt?
Thanks.
This wouldn't be very portable. system calls are often frowned upon, but just to answer your question, the system function does work with the commands you're aiming to use.
For example:
system("notepad.exe my_file.txt");
system("del my_file.txt");
system("pause");
This will open up a file called my_file.txt in notepad, delete it and pause the program.
Again, this is not portable. It's specific to Windows Operating systems.
In fact, I don't even think it's guaranteed to work on all releases of Windows.
(Don't quote me on that.)
On topic: You could start cmd via "CreateProcess" and send key input via window messages ("SendMessage").
I think you should rethink how you want things to be done. The command prompt is not a kind of API base to do things on windows. It's a tool to do things and get information without writing your own program. If you wirte an own program, you should directly use the WinAPI.
To get started you can google "winapi [whatever you want to do]". In your example "winapi start executable" and you will find functions like "CreateProcess" and "ShellExecute".
Perhaps there is a misunderstanding here (if so, I apologize), but the standard way to "further interact with cmd prompt" is via command-line commands, and the standard way "to write a program to control the windows cmd prompt" is via a Batch file. For example, the following Batch file open the cmd prompt (when it is executed via a double click in the Explorer), go to a specific directory (C:/Program Files/) and run an exe in that folder:
#echo off
cd "C:/Program Files/"
nameOfTheProgram.exe

Windows user home folder in C (MinGW)

I'm trying to port an application written in C from linux to windows.
At the moment I'm done fixing the 'hard' parts like missing posix features and the like.
The application compiles, links and works on Windows now (except for the fork() stuff which will be replaced with windows service code later).
The only problem I'm having now is that within the MSYS shell it all works (this maps unix paths for me).
Outside of the MSYS shell it won't work because ~ is not available.
I'm looking for the best way to set the windows user home within my #ifdef stuff.
I read about %USERPROFILE% somewhere but that doesn't seem to work.
Use SHGetKnownFolderPath (Vista+) or SHGetFolderPath depending on your Windows version.
I think you should use the SHGetFolderLocation API:
http://msdn.microsoft.com/en-us/library/bb762180%28VS.85%29.aspx
well not enought, you should even retrieve the ID of the user folder, but by starting at the doc location above you should have all what you neeed.
This should works on any windows version.

Resources