How do I reference txt files in a folder using c

How to I reference a folder within my project. It contains txt files that I need my code to read from these files. Using #c.

To clarify for us, do you mean C# (C Sharp) or regular C?

Here’s an example of how to do it in C…

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

int main() {
    DIR *dir;
    struct dirent *entry;

    // Open the directory
    dir = opendir("path/to/your/folder");
    if (dir == NULL) {
        printf("Failed to open the directory.\n");
        return 1;

    // Read files from the directory
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_REG) {  // Regular file
            if (strstr(entry->d_name, ".txt") != NULL) {  // Check for .txt extension
                // Read the file
                char file_path[256];
                snprintf(file_path, sizeof(file_path), "path/to/your/folder/%s", entry->d_name);
                FILE *file = fopen(file_path, "r");
                if (file == NULL) {
                    printf("Failed to open the file: %s\n", entry->d_name);

                // Read file contents
                char buffer[256];
                while (fgets(buffer, sizeof(buffer), file) != NULL) {
                    // Process the file contents
                    // ...

                // Close the file

    // Close the directory

    return 0;

And here is C#:

using System;
using System.IO;

class Program
    static void Main()
        string folderPath = @"path\to\your\folder";

        // Get all text files in the folder
        string[] filePaths = Directory.GetFiles(folderPath, "*.txt");

        foreach (string filePath in filePaths)
            // Read the file
            string[] lines = File.ReadAllLines(filePath);

            // Process the file contents
            foreach (string line in lines)
                // Process the line

Does this help or would you like an explanation? :grin:


c programming. Sorry for the confusion

1 Like

Did it help you? (for the C version I provided) or did you want an explanation