I just wanted to ask if it's possible to read to a specific file format, say if I wanted to read from a file that has a format of something "info.uc" or "main.uc", how would I go about doing that in C?

This is a little something I am making and I want to know how to read from a specific text file format:

#include "include/load_uc_file.h"

bool find_file_format()
{
    FILE* fileptr;

    fileptr = fopen("", "r");

    if (fileptr == NULL)
    {
        printf("The file was not found");
    }

    return false;
}

If anyone has an answer to this, that would be great.

21 Replies 21

The first argument of fopen should be the name of the file, not an empty string!

Oh no as in how can I read a file but like any file that has a file format that is ending in .uc or something. rather than specifying the exact file every time.

I do not understand your issue: the code you provided is a standard "open file" function and it should work if you correctly give to fopen the name of the file you want (e.g. fopen("info.uc", "r");).

Furthermore, if you have issues with the pointer being NULL, it probably means that the file does not exists, here you can find more on fopen's file access flags and their behaviour.

To respond to OP's previous comment: that's up to you! You can ask directly to the user to specify some files or you can scan a given directory for those you need; it depends by your necessities.

So you want to iterate a folder or given location for any .uc files inside them?

"I just wanted to ask if it's possible to read to a specific file format..." - Absolutely. You can read any file format in C.

If you also want to understand what it is that you are reading, you also have to know the file format. What is the specification for these .uc files? Without knowing that, you'll have a hard time getting any useful information out of what you read from the files.

Regarding: "Oh no as in how can I read a file but like any file that has a file format that is ending in .uc or something..."

Start easy: Require the user of your program to supply a list of the files that the program should read. Your main could look something like this:

#include <stdio.h>

int main(int argc, char* argv[]) {
    if (argc < 2) {
        fprintf(stderr, "USAGE: %s uc-files...\n", argv[0]);
        return 1;
    }

    for (int idx = 1; idx < argc; ++idx) {
        FILE* fp = fopen(argv[idx], "r"); // or "rb" if .uc is a binary file format
        if (fp) {
            // process the file here
            fclose(fp);
        } else {
            perror(argv[idx]); // failed to open the file so print an error
        }
    }
}

Sorry @Ted Lyngmo but I can't really comprehend this C code with my monkey brain. Is it fine if you could make this a little simple?

Thank You!

The previously posted code which you are having trouble understanding is simply the code for the basic structure of a program which allows the user to enter several .uc files on the command-line and process these files individually in a loop. You can look up the documentation of any of the functions used for example here: fprintf, perror

If you are unfamiliar with the meaning of argc and argv or what a for loop is, or if you feel overwhelmed by the documentation of the individual functions, then I suggest that you first read a beginner's book on C, or if you prefer learning from videos, I suggest that you take the free version of the Harvard CS50 course.

By the way, you have not yet answered a previous question which was asked by someone else:

So you want to iterate a folder or given location for any .uc files inside them?

If that is what you want, then plain C does not provide a way to do that. You will have to revert to platform-specific solutions. For example, on Microsoft Windows, you would have to use the function FindFirstFile, and on Linux, the solution is different.

I presume that you want to do something like fopen("*.uc", "r") but suppose there is more than one matching file? You would need a findfirst() ... findnext() type of construction to iterate through the files.

Your example function always returns false, and if a file was found, you've left it open with a file pointer that is inaccessible.

The question needs clarity about what your trying to achieve. For example it isn't clear what has a specific format. Is it the file name or its content? If the content, what is its format? As it stands the question is too broad and unanswerable.

What is the content of the .uc file? There are several files types that use the extension .uc. For example, is it in USEARCH cluster format? Or is it UnrealScript class? Both of these file types use the extension .uc. Or is it something else, maybe a file format that you defined yourself?

It is easy to read the content of an entire file byte by byte, without knowing the file format. However, in order to interpret these bytes values, you need to know which file format is being used.

Re: "I can't really comprehend this C code" - It is very basic C code that you'll understand once you've read all the chapters up to, and including, the chapter on file handling in any good C book. If you haven't done that reading yet, I suggest you do, because otherwise you won't be able to get much done or understand many of the answers you get here.

@TedLyngmo, The fopen() function is not documented to set errno, so the value of errno can be anything: "The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in this International Standard."

Implementations can set errno based on an error, (and IME most common ones do), but they're also free to munge errno to a nonsensical value in any fopen() call.

@AndrewHenle:

I believe POSIX does guarantee that fopen sets errno. But you are correct that ISO C does not guarantee this.

Therefore, instead of

perror(argv[idx]);

a more robust and portable program would do

errno = 0;

before the fopen function call, and then instead of

perror(argv[idx]);

would write:

if ( errno != 0 )
    perror( argv[idx] );
else
    fprintf( stderr, "%s: Error opening file\n", argv[idx] );

@Andrew Henle True! It's like Andreas Wenzel said: It's guaranteed in POSIX compliant environments - and Andreas' workaround should do the trick.

"info.uc" is a not a "format" -- it's a name. "Format" relates to the content of the file, which may or may not be different from any other file with a similar or different name. To properly read a file with another kind of of content/format, you adjust the code and logic that comes after fopen().

@AndreasWenzel, that a function is not documented to set errno is by no means a reliable indication that it will leave errno unmodified. In fact, the spec explicitly says that those standard library functions not documented to set errno may arbitrarily set it to any non-zero value, whether an error occurs or not. An if ( errno != 0 ) test is flatly inappropriate for determining anything about the the success or failure of such a function.

C's I/O utilities treat files as streams of bytes or characters; they don't care about any particular file structure (comma-delimited, XML, JSON, whatever).

If your input file format is more complicated than just a stream of characters or words or numbers, you will have to write the code to parse that format yourself (or use an exiting library like cJSON for JSON files or libxml2 for XML).

I think this discussion here is getting out of hand. We don't even know exactly what the OP wants.

@JohnBollinger: I never suggested to use the condition if ( errno != 0 ) in order to test whether fopen failed or not. In particular, I never suggested to remove the condition if (fileptr == NULL) and to replace it with if ( errno != 0 ). The condition if ( errno != 0 ) should only be used as an additional condition in the case of a failure, in order to determine whether to call perror or not.

I am assuming that if fopen fails and changes errno to a non-zero value, that this new value of errno represents the error. You are correct that this assumption of mine is not guaranteed by the standard. It is nevertheless a reasonable assumption.

The main advantage of my version is that on platforms on which fopen does not set errno, you will not get misleading error messages such as "info.uc: No error", which you would get when always calling perror on fopen failure, as in the original perror code posted by @TedLyngmo.

@Martheen to answer your question: Yes I want to have it so that it scans and try to find the .uc file in them.

@Andreas Wenzel to answer your question: Yeah sure I will look at the book on C. And also the .uc file will be a file type the user can read and write to. It is just a plane file with a random file type I gave it cuz I wanna practice making something.

@greg spears to answer you question: No as in like the name of the file can be anything but when getting the file's format it have be a ".uc".

@John Bode to answer your question: Ah ok I see that I will figure that out when I get there soon I am mostly focusing on the other thing right now, thanks tho!

If you want to create your own file format, then you will have to decide how you want the file to be structured. Do you want the file to consist of binary data or text? If you want it to consist of text, then how should this text be structured? Do you want it to use XML or JSON? Or maybe a simpler structure, such as CSV? Or maybe a much simpler structure, like having one single word per line?

Your Reply

By clicking “Post Your Reply”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.