Thursday, June 6, 2024
AI, Linux & C
The challenge with Linux and X11 (display server) stems from the insufficient online documentation available. When thinking about Linux, the first thing that often comes to mind for laypeople is the terminal. However, Linux encompasses much more than just a terminal. One aspect I particularly value is the capability for a "headless installation." This allows for an operating system without a desktop interface. Therefore, we operate the OS solely in terminal mode and access the desktop using the command "startx." X11 presents certain security challenges, yet we can simply exit X11 and revert to the terminal. For instance, when we need to update the operating system, we either leave X11 or restart it and carry out the update via the terminal.
AI assistant instead of documentation
Fortunately, today we have access to a plethora of new technologies that can offer us support. Even better, the terminal functions as a textual input/output interface, similar to those used by modern AI assistants. This means we can pose questions to AI about bash commands, and if something is incorrect, we can quickly copy and paste the results into the AI assistant. Subsequently, we receive an explanation or a corrected command.
AI as an aid in learning the C language
After installing Linux, you might want to try programming in C. Previously, you had to spend hours searching for information and watching videos, often without significant progress. The C language combines excellently with AI assistants due to the KISS principle, which stands for "keep it small and simple." This means we can work gradually, step by step, with the support of an AI assistant, simplifying the learning process function by function.
First we install the basic packages:
sudo apt update
sudo apt install build-essential
Then in free ChatGPT v3.5:
I'm using Ubuntu how do I compile C hello world program?
We get instruction to create hello.c file with content:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
Ant after that in Terminal:
$ gcc -o hello hello.c
Now we have "hello" executable:
$ ./hello
Hello, World!
OK, let's do something more advanced:
"can you make me simple text writing app in linux terminal using c"
In response, I received C code that we compile:
include <stdio.h>
#include <stdlib.h>
int main() {
char filename[100], text[1000];
printf("Enter a filename to save your text: ");
scanf("%s", filename);
FILE *file = fopen(filename, "w");
if (file == NULL) {
printf("Error opening file!\n");
exit(1);
}
printf("Write your text (press CTRL+D to save and exit):\n");
while (fgets(text, sizeof(text), stdin) != NULL) {
fputs(text, file);
}
fclose(file);
return 0;
}
To test AI I will use: “Create me simple X11 paint app and show me how to compile it”. ChatGPT v3.5 has failed but v4 have gave me working code:
/*
COMPILE:
sudo apt-get install libx11-dev #if missing
gcc -o paint_app app.c -lX11
./paint_app
*/
#include <X11/Xlib.h>
int main() {
Display *dpy;
Window root, win;
GC gc;
XEvent ev;
int x_prev = 0, y_prev = 0;
int x_cur, y_cur;
dpy = XOpenDisplay(NULL);
root = DefaultRootWindow(dpy);
win = XCreateSimpleWindow(dpy, root, 0, 0, 640, 480, 0, 0, WhitePixel(dpy, 0));
XSelectInput(dpy, win, ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask);
XMapWindow(dpy, win);
gc = XCreateGC(dpy, win, 0, NULL);
while (1) {
XNextEvent(dpy, &ev);
switch (ev.type) {
case Expose:
XSetForeground(dpy, gc, WhitePixel(dpy, 0));
XFillRectangle(dpy, win, gc, 0, 0, 640, 480);
XSetForeground(dpy, gc, BlackPixel(dpy, 0));
break;
case ButtonPress:
x_prev = ev.xbutton.x;
y_prev = ev.xbutton.y;
break;
case MotionNotify:
x_cur = ev.xmotion.x;
y_cur = ev.xmotion.y;
if (ev.xmotion.state & Button1Mask) {
XDrawLine(dpy, win, gc, x_prev, y_prev, x_cur, y_cur);
}
x_prev = x_cur;
y_prev = y_cur;
break;
}
}
XFreeGC(dpy, gc);
XDestroyWindow(dpy, win);
XCloseDisplay(dpy);
return 0;
}
AI helping me create bash scripts
Prompt: if i have multiple c files can you show me example on how to compile that in single bash script
This is a Bash script that compiles several C files. The script simplifies the process of compiling multiple C files by tracking each source file and creating a corresponding executable file without the ".c" extension.
#!/bin/bash
# List of C source files
files=("file1.c" "file2.c")
# Compile each C file
for file in "${files[@]}"; do
output_name="${file%.c}" # Remove the '.c' extension
gcc -o "$output_name" "$file"
done
Prompt: can you write me bash script that will rename all files in current dir and add current date at end of each file
This is a Bash script that renames all files in the current directory by appending the current date to the end of each file name.
#!/bin/bash
# Get the current date in the format YYYYMMDD
current_date=$(date +"%Y%m%d")
# Iterate through each file in the current directory
for file in *; do
# Check if it's a regular file
if [ -f "$file" ]; then
# Extract the file extension (if any)
extension="${file##*.}"
# Remove the extension from the original filename
filename_no_ext="${file%.*}"
# Append the current date and the original extension (if any)
new_filename="${filename_no_ext}_${current_date}.${extension}"
# Rename the file
mv "$file" "$new_filename"
echo "Renamed: $file to $new_filename"
fi
done
Having fun with C Functions
We can segment our project with functions while using AI. All we need to specify is input, output and what we want function to do in AI prompt. For example, to start, we can define a function that enables reading text from a document:
#include <stdio.h>
#include <stdlib.h>
char *loadFileToString(const char *filePath) {
FILE *file = fopen(filePath, "r");
if (file == NULL) {
fprintf(stderr, "Error opening file: %s\n", filePath);
return NULL;
}
// Determine the size of the file
fseek(file, 0, SEEK_END);
long fileSize = ftell(file);
fseek(file, 0, SEEK_SET);
// Allocate memory for the file content
char *fileContent = (char *)malloc(fileSize + 1); // +1 for null-terminator
if (fileContent == NULL) {
fclose(file);
fprintf(stderr, "Memory allocation failed.\n");
return NULL;
}
// Read the file content into the allocated memory
size_t bytesRead = fread(fileContent, 1, fileSize, file);
fileContent[bytesRead] = '\0'; // Null-terminate the string
fclose(file);
return fileContent;
}
int main() {
const char *filePath = "./demo.txt"; // Replace with your file path
char *fileContent = loadFileToString(filePath);
if (fileContent != NULL) {
// Print the loaded content
printf("%s", fileContent);
// Remember to free the allocated memory when done
free(fileContent);
}
return 0;
}
Anything we don't understand, we ask the AI, request it to write functions for us, and how to organize the entire project.
Free AI chat
You can use
DuckDuckGo AI chat with four models.