Createfile function - c

I am creating the file using Createfile function.
The C program is working fine but I am unable to see the created file in the respective folder.
Also "view hidden files" option is checked.

You can check if the function worked correctly by checking out the returned HANDLE value.
edit: A C program continues to function (incorrectly though) if a functions fails. It's therefore very important to check each and every returned HANDLE.
edit: The returned HANDLE should not be INVALID_HANDLE_VALUE. (But I can imagine that NULL isn't good either).

Two things to check for. Number one, did it actually succeed? From the docs:
Return Value
If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot.
If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
Number two, are you looking in the right place. Frequently, people who run their code from within an IDE don't realise that their current working directory is not always what they think it is. You can system("cd"); or something similar to see what it actually is.
Or, you can use absolute pathnames to ensure the file is being created at the right place (for testing, that is - you should never use absolute paths for production code).
If neither of those two suggestions help, you should post the code that shows the particular problem. Preferably enough so that we don't have to come back and ask for more.

Related

A function returning "ENOTDIR", "EBUSY", etc. as strings?

strerror() function returns a short error description, given error number as argument. For example, if the argument is ENOTDIR, it will return "Not a directory", if the argument is EBUSY, it will return "Device or resource busy", etc.
But, is there a function that returns "ENOTDIR" for argument equals ENOTDIR, "EBUSY" for argument EBUSY, etc.?
I just want to avoid writing a huge switch statement for this purpose.
No- there is no standard or commonly used nonstandard function that provides this functionality.
One approach would be to write a huge switch statement, but this might not be the best approach for you to take. Most values of errno are not specified by any standard, so their values may or may not be consistent across different operating systems or even different versions of the same operating system.
Plus it would be a pain in the rear end.
A more elegant approach, if some runtime overhead is acceptable, would be to write a function that looks up these errors codes when they occur, rather than hard-coding the values into a big table. GNU/Linux systems have a list of all possible errno values at:
/usr/include/asm-generic/errno-base.h
/usr/include/asm-generic/errno.h
These files provide a #define of each errno value along with their value and a short description in an adjacent comment. It'd be pretty trivial to search these files line-by-line and print out the matching error code. Even if not, these files would be the things to start with in your quest to write a huge switch statement.
Beware that the kernel might negate these values when they're passed to userspace.
As David points out above, the problem is there is no standard function that can provide the desired functionality. So thinking that this would be a neat problem to try to write a script for, I wrote a little something to automatically generate the switch function (if it should come to be necessary) and posted the code here. Seems to work alright on OS X, otherwise mileage may vary. A script such as this could be added to the build process to make sure that the values were defined correctly.

Test if a file is deletable

Is there any way to determine if a file can be deleted before trying DeleteFile on it. I just want to test if a DeleteFile will succeed without really deleting the file. What I want to do is to create a hardlink to a file if it is not in use and to copy it if it is in use without FILE_SHARE_DELETE(there is in the system a handle opened on it woithout FILE_SHARE_DELETE flag).
Thank you!
Disclaimer: I don't really know anything about Windows programming. But I read documentation.
According to the MSDN documentation for CreateFile, you can specify DELETE in the dwDesiredAccess parameter, which will cause the CreateFile call to fail if the access right is not available. (You can also specify OPEN_EXISTING for dwCreationDisposition if you don't actually want to create a new file.) That should cover your use case.
However, it's worth pointing out that there is an race condition; you might do this test and then just afterwards, before you have a chance to act on the result, someone else might open the file without the FILE_SHARE_DELETE. So for the test to be meaningful, you'd need to know more about the lifecycle of files than is mentioned in your question (which you indeed might know; it isn't really necessary to mention it, so if you do, just ignore this paragraph.)
Thank you everyone for your answers. In the end after 3 days of searching(after 2 days I posted my question here) I found I needed. At the beginning (3 days ago) I thought DELETE flag is enough for the test, but it does not work - I still am able to open a handle even there is another handle open in the system without FILE_SHARE_DELETE flag. Anyway, starting from here I manage to find a solution in the end - making a CreateFile with FILE_FLAG_DELETE_ON_CLOSE - if I receive a valid handle than the file is deletable. Before closing the handle using NtSetInformationFile with FILE_DISPOSITION_INFORMATION I remove FILE_FLAG_DELETE_ON_CLOSE so this way I avoid deleting the file when closing the handle. And indeed I do have control over the lifecycle of that file - meaning that after I make the test no one should open it without SHARE_DELETE - at least not the processes I control which should be enough for what I have to do.

Is it a bad practice to output error messages in a function with one input and one output [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I was once told that functions with one input and one output(not exactly one) should not print messages when being called. But I don't understand. Is it for security or just for convention?
Let me give an example. How to deal with an attempt that access data in a sequential list with an incorrect index?
// 1. Give out the error message inside the function directly.
DataType GetData(seqList *L, int index)
{
if (index < 0 || index >= L->length) {
printf("Error: Access beyond bounds of list.\n");
// exit(EXIT_FAILURE);
}
return L->data[index];
}
// 2. Return a value or use a global variable(like errno) that
// indicates whether the function performs successfully.
StateType GetData(seqList *L, int index, int *data)
{
if (index < 0 || index >= L->length) {
return ERROR;
}
*data = L->data[index];
return OK;
}
I think there are two things going on here:
Any visible and unexpected side-effect such as writing to streams is generally bad, and not just for functions with one input and one output. If I was using a list library, and it started silently writing error messages to the same output stream I was using for my regular output, I'd consider that a problem. However, if you are writing such a function for your own personal use, and you know ahead of time that the action you want taken is always to print a message and exit(), then it's fine. Just don't force this behavior on everyone else.
This is a specific case of the general problem of how to inform callers about errors. A lot of the time, a function cannot know the correct response to an error, because it doesn't have the context that the caller does. Take malloc(), for instance. The vast majority of the time, when malloc() fails, I just want to terminate, but once in a great while I might want to deliberately fill the memory by calling malloc() until it fails, and then proceed to do something else. In this case, I don't want the function to decide whether or not to terminate - I just want it to tell me it's failed, and then pass control back to me.
There are a number of different approaches to handling errors in library functions:
Terminate - fine if you're writing a program yourself, but bad for a general purpose library function. In general, for a library function, you'll want to let the caller decide what to do in the case of an error, so the function's role is limited to informing the caller of the error.
Return an error value - sometimes OK, but sometimes there is no feasible error value. atoi() is a good case in point - all the possible values it returns could be correct translations of the input string. It doesn't matter what you return on error, be it 0, -1 or anything else, there is no way to distinguish an error from a valid result, which is precisely why you get undefined behavior if it encounters one. It's also semantically questionable from a slightly purist point of view - for instance, a function which returns the square root of a number is one thing, but a function which sometimes returns the square root of a number, but which sometimes returns an error code rather than a square root is another thing. You can lose the self-documenting simplicity of a function when return values serve two completely separate purposes.
Leave the program in an error state, such as setting errno. You still have the fundamental problem that if there is no feasible return value, the function still can't tell you that an error has occurred. You could set errno to 0 in advance and check it afterwards every time, but this is a lot of work, and may just not be feasible when you start involving concurrency.
Call an error handling function - this basically just passes the buck, since the error function then also has to address the issues above, but at least you could provide your own. Also, as R. notes in the comments below, other than in very simple cases like "always terminate on any error" it can be asking too much of a single global error handling function to be able to sensibly handle any error that might arise in a way that your program can them resume normal execution. Having numerous error handling functions and passing the appropriate ones individually to each library function is technically possible, but hardly an optimal solution. Using error handling functions in this way can also be difficult or even impossible to use correctly in the presence of concurrency.
Pass in an argument that gets modified by the function if it encounters an error. Technically feasible, but it's not really desirable to add an additional parameter for this purpose to every library function ever written.
Throw an exception - your language has to support them to do this, and they come along with all kinds of associated difficulties including unclear structure and program flow, more complex code, and the like. Some people - I'm not one of them - consider exceptions to be the moral equivalent of longjmp().
All the possible ways have their drawbacks and advantages, as of yet humanity has not discovered the perfect way of reporting errors from library functions.
In general you should make sure you have a consistent and coherent error handling strategy, which means considering whether you want to pass an error up to a higher level or handle it at the level it initially occurs. This decision has nothing to do with how many inputs and outputs a function has.
In a deeply embedded system where a memory allocation failure occurs at a critical juncture, for example, there's no point passing that error back up (and indeed you may well not be able to) - all you can do might be enter a tight loop to let the watchdog reset you. In this case there's no point reserving invalid return values to indicate error, or indeed in even checking the return value at all if it doesn't make sense to do so. (Note I am not advocating just lazily not bothering to check return values, that is a different matter entirely).
On the other hand, in a lovely beautiful GUI app you probably want to fail as gracefully as possible and pass the error up to a level where it can be either worked around / retried / whatever is appropriate; or presented to the user as an error if nothing else can be done.
It is better to use perror() to display error messages rather than using printf()
Syntax:
void perror(const char *s);
Also error messages are supposed to be sent to the stderr stream than stdout.
Yes, it's a bad practice; even worse is that you're sending the output to stdout rather than stderr. This could end up corrupting data by mixing error message in with output.
Personally, I believe very strongly that this kind of "error handling" is harmful. There is no way you can validate that the caller passed a valid value for L, so checking the validity of index is inconsistent. The documented interface contract for the function should simply be that L must be a valid pointer to an object of the correct type, and index a valid index (in whatever sense is meaningful to your code). If an invalid value for L or index is passed, this is a bug in your code, not a legitimate error that can occur at runtime. If you need help debugging it, the assert macro from assert.h is probably a good idea; it makes it easy to turn off the check when you no longer need it.
One possible exception to the above principle would be the case where the value of L is coming from other data structures in your program, but index is coming from some external input that's not under your control. You could then perform an external validation step before calling this function, but if you always need the validation, it makes sense to integrate it like you're doing. However, in that case you need to have a way to report the failure to the caller, rather than printing a useless and harmful message to stdout. So you need to either reserve one possible return value as an error sentinel, or have an extra argument that allows you to return both a result and an error status to the caller.
Return a reserved value that's invalid for a success condition. For example, NULL.
It is advisable not to print because:
It doesn't help the calling code reason about the error.
You're writing to a stream that might be used by higher level code for something else.
The error may be recoverable higher, so you might be just printing misleading error messages.
As others have said, consistency in how you deal with error conditions is also an important factor. But consider this:
If your code is used as a component of another application, one that does not follow your printing convention, then by printing you're not allowing the client code to remain faithful to its own strategy. Thus, using this strategy you impose your convention to all related code.
On the other hand, if you follow the "cleaner" solution of returning a reserved value and the client code wants to follow the printing convention, the client code can easily adapt to what you return and even print an error, by making simple wrappers around your functions. Thus, using this strategy you give the users of your code enough space to choose the strategy that best works for them and to be faithful to it.
It is always best if code deals with one thing only. It is easier to understand, it is easier to use, and is applicable in more instances.
Your GetData function that prints an error message isn't suitable for use in cases where there may not be a value. i.e. The calling code wants to try to get a value and handle the error by using a default if it doesn't exist.
Since GetData doesn't know the context it can't report a good error message. As an example higher up the call stack we can report hey you forgot to give this user an age, vs in GetData where all it knows is we couldn't get some value.
What about a multithreaded situation? GetData seems like it would be something that might get called from multiple threads. With a random bit of IO shoved in the middle it will cause contention over who has access to the console if all the threads need to write at the same time.

How would I go about checking the file system I'm working on in C

I'm making a program and one of the things it needs to do is transfer files. I would like to be able to check before I start moving files if the File system supports files of size X. What is the best way of going about this?
Go on with using a function like ftruncate to create a file of the desired size in advance, before the moving, and do the appropriate error-handling in case it fails.
There's no C standard generic API for this. You could simply try creating a file and writing junk to it until it is the size you want, then deleting it, but even that isn't guaranteed to give you the info you need - for instance another process might have come and written a large file in between your test and your transfer, taking up space you were hoping to use.

How to handle labels in a scripting language I'm writing?

So I've been stewing over this for a long time, thinking about it. Here's a code example first, and then I'll explain it.
:main
dostuff
otherlabel
:otherlabel
dostuff
Alright so in this example, main is where the code starts, and it 'calls' the label 'otherlabel'. This is really just a shortcut for a jump command that changes execution to a different location in memory. My problem though is, how do I handle these labels so that they don't have to be declared before they are called?
At the moment, I'm doing a single step compilation reading straight from the source and outputting the bytecode. I am simply handling labels and adding them to a dictionary when I find them. And then I replace 'otherlabel' with a jump command to the correct location in code. But in this case that code wouldn't compile.
I've thought of a few ways to do this:
First is handling labels before anything else but this requires me to do everything in two steps and I have to deal with the same code twice, this slows down the process and just seems like a mess.
Second is queueing up the label calls until AFTER I've gone through the entire file and compiled everything else and then dealing with them, this seems much cleaner.
I'm writing this in C so I'd rather not implement complex data structures, I'm looking for the most straight forward way to handle this.
Use multiple passes. One pass isn't going to suffice for a scripting language, especially when you are getting to the more complex structures.
In a first pass, before compiling, construct your dictionary of labels.
In a later pass, when the compiling happens, just use that dictionary.
You could use "backpatching", although it sounds like that's what you've tried already; and it could be consstrued as a complex structure.
When you encounter a call to an undefined label, you emit the jump with a blank address field (probably into a buffer, otherwise this becomes the same as "multipass" if you have to re-read the file to patch it); and you also store a pointer to the blank field in a "patch-up" list in the dictionary. When you encounter the label definition, you fill-in all the blanks in the list, and proceed normally.

Resources