Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C แสดงไฟล์และโฟลเดอร์ทั้งหมดในไดเรกทอรี

การดำเนินการกับไฟล์

การดำเนินการกับไฟล์ใน C ประกอบด้วย:

  • ตั้งชื่อไฟล์
  • เปิดไฟล์
  • อ่านจากไฟล์
  • เขียนลงไฟล์
  • ปิดไฟล์

ไวยากรณ์

การเปิดและตั้งชื่อไฟล์

FILE *File_pointer;
File_pointer = fopen("File name", "mode");

การอ่านจากไฟล์

int fgetc(FILE *fp); // อ่านตัวอักษรเดี่ยว

การเขียนลงไฟล์

int fputc(int c, FILE *fp); // เขียนตัวอักษรเดี่ยว

ตรรกะการแสดงไฟล์และโฟลเดอร์

dr = opendir(".");
if(dr != NULL) {
    printf("List of Files & Folders:-\n");
    for(d = readdir(dr); d != NULL; d = readdir(dr)) {
        printf("%s\n", d->d_name);
    }
    closedir(dr);
}

ตัวอย่างโค้ด

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

int main() {
    struct dirent *d;
    DIR *dr;
    dr = opendir(".");
    if(dr != NULL) {
        printf("List of Files & Folders:-\n");
        for(d = readdir(dr); d != NULL; d = readdir(dr)) {
            printf("%s\n", d->d_name);
        }
        closedir(dr);
    } else {
        printf("\nerror while opening the directory!");
    }
    getch();
    return 0;
}

ผลลัพธ์

List of Files & Folders:-
.
..
accessing array.c
accessing array.exe
accessing array.o
bhanu.txt
C Programs
convert 2 digit no into english word.c
convert 2 digit no into english word.exe
convert 2 digit no into english word.o
DATA
delete vowels in string.c
delete vowels in string.exe
delete vowels in string.o
emp.txt
EVEN ex.c
ex.exe
ex.o
example pro.c
example pro.exe
example pro.o
fibbinoci serie.c
fibbinoci serie.exe
fibbinoci serie.o
file
file example1.c
file example1.exe
file example1.o
file example2.c
file example2.exe
file example2.o
implicit conversion.c
implicit conversion.exe
implicit conversion.o
leap year.c
leap year.exe
leap year.o
little n big endian.c
little n big endian.exe
little n big endian.o
work out examples