0% found this document useful (0 votes)
2 views

Linux file operations

This document provides a comprehensive guide on executing C programs in Linux, detailing the installation of the GCC compiler, writing, compiling, and running a C program. It also covers file and directory operations, including functions for opening, reading, writing, and closing files, as well as handling directories. Additionally, it includes example code snippets and explanations for file handling and directory listing in C.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Linux file operations

This document provides a comprehensive guide on executing C programs in Linux, detailing the installation of the GCC compiler, writing, compiling, and running a C program. It also covers file and directory operations, including functions for opening, reading, writing, and closing files, as well as handling directories. Additionally, it includes example code snippets and explanations for file handling and directory listing in C.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

To execute C programs in Linux, follow these steps:

Step 1: Install GCC Compiler (If Not Installed)

GCC (GNU Compiler Collection) is used to compile C programs.


Check if GCC is installed by running:

gcc --version

If GCC is not installed, install it using:

 Ubuntu/Debian:

sudo apt update && sudo apt install gcc

Step 2: Write a C Program

Create a C file using a text editor.

For example, use nano or vim:

nano example.c

Write a simple C program inside:

#include <stdio.h>

int main() {
printf("Hello, Linux System Calls!\n");
return 0;
}

Save the file (CTRL + X, then Y, then Enter in nano).

Step 3: Compile the C Program

Use the gcc command to compile:

gcc example.c -o example

 example.c → Source file.


 -o example → Output executable named example.

If there are no errors, this will generate an executable file called example.

Step 4: Run the Compiled Program

Execute the compiled program using:


./example

Expected Output:

Hello, Linux System Calls!

Step 5: Debugging (If Needed)

If you get errors, check the error messages and fix them.
For debugging, you can compile with -g for GDB (GNU Debugger):

gcc -g example.c -o example

Run the program in GDB:

gdb ./example

Step 6: Run a Program with Required Permissions

If a program requires root privileges (e.g., system file access), use:

sudo ./example

Additional Compilation Flags

1. Enable Warnings:
2. gcc -Wall example.c -o example
3. Optimize Performance:
4. gcc -O2 example.c -o example
5. Enable Debugging Mode:
6. gcc -g example.c -o example

File Operations (open, read, write, close, fcntl, seek, stat)

These functions are used to perform file operations such as opening, reading, writing,
seeking, and getting file information.

(1) open() - Open a File

fd = open("example.txt", O_CREAT | O_RDWR, 0644);

 Opens or creates a file for reading and writing.


 Parameters:
o "example.txt" → File name.
o O_CREAT → Creates the file if it does not exist.
o O_RDWR → Opens the file for both reading and writing.
o 0644 → Sets file permissions:
 6 (110) → Read & Write for owner.
 4 (100) → Read for group.
 4 (100) → Read for others.
 Returns:
o A file descriptor (integer) if successful.
o -1 on failure.

(2) write() - Write to a File

write(fd, "Hello, Linux System Calls!", 26);

 Writes data to the file.


 Parameters:
o fd → File descriptor.
o "Hello, Linux System Calls!" → Data to write.
o 26 → Number of bytes to write.
 Returns:
o Number of bytes written.
o -1 on failure.

(3) lseek() - Move File Pointer

lseek(fd, 0, SEEK_SET);

 Moves the file pointer to a specified position.


 Parameters:
o fd → File descriptor.
o 0 → Offset (position in bytes).
o SEEK_SET → Moves to the start of the file.
 Returns:
o New file offset on success.
o -1 on failure.

(4) read() - Read from a File

read(fd, buffer, 26);

 Reads data from the file.


 Parameters:
o fd → File descriptor.
o buffer → Buffer to store the data.
o 26 → Number of bytes to read.
 Returns:
o Number of bytes read.
o 0 if end-of-file is reached.
o -1 on failure.

(5) stat() - Get File Information


struct stat file_stat;
stat("example.txt", &file_stat);
printf("File size: %ld bytes\n", file_stat.st_size);

 Retrieves file metadata (size, permissions, timestamps, etc.).


 Parameters:
o "example.txt" → File name.
o &file_stat → Pointer to a stat structure to store file info.
 Returns:
o 0 on success.
o -1 on failure.

(6) close() - Close a File

close(fd);

 Closes the file and releases system resources.


 Parameters:
o fd → File descriptor.
 Returns:
o 0 on success.
o -1 on failure.

2. Directory Handling Functions

These functions are used for working with directories.

(1) opendir() - Open a Directory

DIR *dir = opendir(".");

 Opens a directory stream.


 Parameters:
o "." → Current directory.
 Returns:
o A pointer to DIR structure if successful.
o NULL on failure.

(2) readdir() - Read Directory Entries

while ((entry = readdir(dir)) != NULL) {


printf("%s\n", entry->d_name);
}

 Reads entries (files, directories) from a directory stream.


 Parameters:
o dir → Pointer to the directory stream.
 Returns:
o A pointer to a dirent structure containing:
 entry->d_name → File or directory name.
o NULL when all entries are read.

(3) closedir() - Close a Directory

closedir(dir);

 Closes the directory stream.


 Parameters:
o dir → Pointer to the directory stream.
 Returns:
o 0 on success.
o -1 on failure.

Functio Description Parameters Return Value


n
open() Opens or creates a File name, flags, File descriptor or -1 on
file permissions failure
write() Writes data to a file File descriptor, buffer, size Bytes written or -1 on
failure
lseek() Moves file pointer File descriptor, offset, New offset or -1 on
mode failure
read() Reads data from a File descriptor, buffer, size Bytes read or -1 on
file failure
stat() Retrieves file File name, pointer to stat 0 on success, -1 on
information structure failure
close() Closes a file File descriptor 0 on success, -1 on
failure
opendir() Opens a directory Directory name DIR * or NULL on
failure
readdir() Reads directory Pointer to DIR stream dirent * or NULL when
entries finished
closedir() Closes a directory Pointer to DIR stream 0 on success, -1 on
failure

Program: File Handling in Linux (open, read, write, close, lseek, fcntl, stat)

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>

int main() {
int fd;
char buffer[100];

// Open a file for reading and writing (create if it doesn’t exist)


fd = open("example.txt", O_CREAT | O_RDWR, 0644);
if (fd == -1) {
perror("Error opening file");
return 1;
}

// Writing to the file


write(fd, "Hello, Linux System Calls!", 26);

// Seek to the beginning


lseek(fd, 0, SEEK_SET);

// Reading from the file


read(fd, buffer, 26);
buffer[26] = '\0';
printf("Read from file: %s\n", buffer);

// Get file information


struct stat file_stat;
if (stat("example.txt", &file_stat) == 0) {
printf("File size: %ld bytes\n", file_stat.st_size);
}

// Close the file


close(fd);
return 0;
}

Compile & Run:

gcc file_handling.c -o file_handling


./file_handling

Step-by-Step Explanation of the Programs

Code:

#include <stdio.h> // For standard input/output functions


#include <fcntl.h> // For file control options (open, fcntl)
#include <unistd.h> // For system calls (read, write, close, lseek)
#include <sys/stat.h> // For file information (stat)

 These header files provide functions for handling files, performing read/write
operations, and retrieving file metadata.

Step 1: Opening a File

fd = open("example.txt", O_CREAT | O_RDWR, 0644);

 open() is used to open or create a file.


 O_CREAT: Creates the file if it does not exist.
 O_RDWR: Opens the file for both reading and writing.
 0644: Sets file permissions (read/write for owner, read-only for others).
 If open() fails, it returns -1.

Step 2: Writing to the File

write(fd, "Hello, Linux System Calls!", 26);

 write(fd, buffer, size) writes size bytes from buffer to the file descriptor fd.
 Here, we write "Hello, Linux System Calls!" (26 characters) to the file.

Step 3: Moving the File Pointer

lseek(fd, 0, SEEK_SET);

 lseek() moves the file pointer.


 SEEK_SET moves the pointer to the beginning of the file.
 This ensures the next read() operation starts from the beginning.

Step 4: Reading from the File

read(fd, buffer, 26);


buffer[26] = '\0';
printf("Read from file: %s\n", buffer);

 read(fd, buffer, size) reads size bytes from fd into buffer.


 We add '\0' at the end to make it a valid string for printing.

Step 5: Getting File Information

struct stat file_stat;


if (stat("example.txt", &file_stat) == 0) {
printf("File size: %ld bytes\n", file_stat.st_size);
}

 stat() retrieves file details (size, permissions, timestamps).


 file_stat.st_size gives the file size.

Step 6: Closing the File

close(fd);

 close(fd) releases the file descriptor.

How to Compile & Run

gcc file_handling.c -o file_handling


./file_handling
 Compiles the program and runs it.

Directory Operations (opendir, readdir, closedir)

Program: Directory Listing in Linux

#include <stdio.h>
#include <dirent.h>

int main() {
struct dirent *entry;
DIR *dir = opendir(".");

if (dir == NULL) {
perror("Error opening directory");
return 1;
}

printf("Files in the current directory:\n");


while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}

closedir(dir);
return 0;
}

Compile & Run:

gcc dir_listing.c -o dir_listing


./dir_listing

Step-by-Step Explanation of the Programs

Step 1: Opening the Directory

DIR *dir = opendir(".");

 opendir() opens a directory.


 "." represents the current directory.
 If the directory fails to open, it returns NULL.

Step 2: Reading Directory Entries

while ((entry = readdir(dir)) != NULL) {


printf("%s\n", entry->d_name);
}

 readdir() reads directory entries one by one.


 entry->d_name gives the file/directory name.

Step 3: Closing the Directory

closedir(dir);

 closedir() closes the directory stream.

How to Compile & Run

gcc dir_listing.c -o dir_listing


./dir_listing

 Lists files in the current directory.

Final Output Example

Files in the current directory:


file_handling.c
dir_listing.c
example.txt

You might also like