My situation is as follows. I obtain FILE * pointer. I know it can point to FILE type that does not support seek (can be PIPE). So to make things easier I thought of loading parts of the file to memory as a string buffer.
The problem is, that my file contains, next to some other stuff, C structures, that I need to load to memory. And so far, everything I have tried had failed.
Most promising seemed to be fmemopen, but when I added it to my code I got
warning: implicit declaration of function ‘fmemopen’ [-Wimplicit-function-declaration]
stream = fmemopen (buffer, p_header.bytes, "r");
warning and that is certainly nothing I want. It remained implicit declared even though I added stdio.h include.
Can anything be done about that? Can I somehow create something of FILE * type in memory so I can call fread on it?
Or is there a way how to read structure from string?
I have used fread as follows:
fread(&var_of_type_love_struct_t, sizeof(love_struct_t), 1, myfile);
The warning about fmemopen is that the compiler didn't find the prototype, add
#define _GNU_SOURCE
before including all the headers, or, if using GCC, add -D_GNU_SOURCE to the options.
Related
Normally I would use fopen but with Visual Studio you have to use the secure variant fopen_s. But because fopen_s returns a NULL pointer if the action was successful, I cannot use the fclose() function to close the connection to the file. fclose(filePointer) is not possible because it is a NULL pointer. If I want to use functions like fwrite() or fread() that doesn't work either.
My Problem is when I use fwrite(str, 1, sizeof(str), filePointer) -> "filePointer could be 0". Of cause its 0 because I get "0" if fopen_s(filePointer) works well.
Unfortunately, I can't find any examples of the security variants anywhere, because everyone uses the "normal" ones. I know that I can switch off the safety function, but I don't really want to do that, because safety is actually something good :D
An example is right there on Microsoft's doco page (abridged here):
FILE *stream;
errno_t err = fopen_s(&stream, "crt_fopen_s.c", "r");
if (err == 0) {
fclose(stream);
}
The first argument to fopen_s is a pointer to the variable that will receive the file handle, so it's that variable that you use to do whatever you need to do to the file (which is just closing it im my example above).
Note that these functions are not safe, though they may be safer than the originals. They check for specific NULL values but there are plenty of unsafe pointers that aren't NULL(a).
It's always been my view that good code design makes these checks unnecessary, though I realise some may disagree(b). Probably one of the first lines I put in my C programs is:
#define _CRT_SECURE_NO_WARNINGS
so as not to have to put up with what I consider to be the Microsoft nanny state.
(a) Such as (void*)42, for example.
(b) They are, of course, wrong. 😀
unix 6th source code. Very old.
conf.h
struct bdevsw {
int (*d_open)();
int (*d_close)();
int (*d_strategy)();
int *d_tab;
} bdevsw[];
conf.c
int (*bdevsw[])(){
&nulldev, &nulldev, &rkstrategy, &rktab,
&nodev, &nodev, &nodev, 0,
0
}
My question why not the initialization just reads,
bdevsw[] = {......}
All the information gathered for this answer is from my trusted copy of the Lions' Commentary book. It's a good resource for the very early UNIX code.
If you pump that monstrosity of a declaration into cdecl, you'll see that its purpose is to:
declare bdevsw as array of pointer to function returning int.
Hence it's not code at all(a), rather it's the array definition for the functions, one per device, pretty much the same as your suggestion would be.
The reason it's not in the header file is probably for the following reasons.
First, the conf.c file is actually auto-generated by mkconf, as that's the file that contains the device details (block and character devices, held in bdevsw and cdevsw) for a given UNIX system.
As an autogenerated file, it makes sense to break apart the declarations of the data types (which are consistent across different systems) and the definitions of the arrays (which do change per system). The comment at the top of this file state that it, and low.s, are the result of mkconf.
Second, there are quite a few C files that include conf.h. For example, bio.c (block I/O), sys3.c (filesystem calls), fio.c (file calls), and alloc.c (very early initialisation to read the root super block).
So, if the array was defined in the header file (presumably as static to prevent double definition), each source file would basically have it's own copy, wasting precious space. By defining it in conf.c, there's one copy shared amongst everyone.
(a) Your comment that:
the second parenthesis in the initialization stmt makes it look like a function
is understandable and, in this case, it does represent a function call. But only insofar that it's an array of pointers to functions, not an actual function definition.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
At first, I was writing my function in an .h file and then include it with #include "myheader.h". Then, someone said me that it's better to add to these files only functions prototypes and to put the real code in a separate .c file.
Now, I'm able to compile more .c files to generate only an executable, but at this point I can't understand why I should add the header files if the code is in another file.
Moreover, I had a look to standard C libraries (like stdlib.h) in the system and it seemed to me to store only structure definitions, constants and similar... I'm not so good with C (and to be honest, stdlib.h was almost Chinese to me, no offense for Chinese of course :) ), but I didn't spot any single line of 'operative' code. However, I always just include it without adding anything else and I compile my files as if the 'code' was actually there.
Can someone please explain me how do these things work? Or, at least, point me to a good guide? I searched on Google and SO, also, but didn't find anything that explains it clearly.
When you compile C code, the compiler has to actually know that a particular function exists with a defined name, parameter list, return type and optional modifiers. All these things are called function signature and the existence of a particular function is declared in the header file. Having this information, when the compiler finds a call to this function, it will know which type of parameters to look for, can control whether they have the appropriate type and prepare them to a structure that will be pushed to the stack before the code actually jumps to your function implementation. However the compiler does not have to know the actual implementation of the function, it simple puts a "placeholder" in your object file to all function calls. (Note: each c files compiles to exactly one object file). #include simple takes the header file and replaces the #include line with the contents of the file.
After the compilation the build script passes all object files to the linker. The linker will be that resolves all function "placeholders" finding the physical location of the function implementation, let them be among your object files, framework libraries or dlls. It simple places the information where the function implementation can be found to all function calls thus your program will know where to continue execution when it arrives to your function call.
Having said all this it should be clear why you can't put function definition in the header files. If later you would #include this header in to more then one c file, both of them would compile the function implementation into two separate object files. The compiler would work well, but when the linker wanted to link together everything, it would find two implementation of the function and would give you an error.
stdlib.h and friends work the same way. The implementation of the functions declared in them can be found in framework libraries which the compiler links to your code "automatically" even if you are not aware of it.
The C language (together with C++) uses a quite obsolete strategy for making the compiler know the functions defined elsewhere.
This strategy goes like this: the signatures of the functions etc. (this stuff is called declarations in C) go into a special file called header, and every other file which wants to use them is expected to almost literally include that header into the file (actually, #include directive just tells the compiler to include the literal text of the header), so that the compiler sees again the function declarations.
Other languages solve this problem in a different way: compiler sees all the source code, and remembers the metadata of the already compiled classes itself.
The strategy used in C shifts the task of finding all the dependencies from the compiler to the developer; it's a legacy from the old times when the computers were small, silly and slow, so this kind of help from the developer was really valuable.
Although this strategy has numerous drawbacks, and besides it's theoretically possible to change it now, the standard is not going to change, because gigabytes of code have been written in that style already.
tl;dr: it's a legacy from the 70's.
In C it is required that a function is declared before it is called. The reason this is required was that in the 70s it would just take too much time to first parse a file for all its symbols and then parse it a second time to actually compile the code. If all functions are declared before they are called one single parse is enough. However on modern system we no longer face those limitations and that is the reason why mondern languages don't have this requirement.
Imagine you have 2 files a.c b.c in your project. You implement a function foo which you want to use in both files. You can't just define the function in a.c and use it in b.c since you have to declare a function before you call it. So you would add a line void foo(); to b.c. But everytime you change the signature of your function in a.c you would have to change the declaration in b.c. To circumvent this issue it is standard strategy in C to declare all functions your file implements in a seperate header file (in this case a.h. The header file is then included by all other files who want to use that code (so b.c would use this: #include "a.h").
An #include is a preprocessor directive that causes the file to be textually inserted at the point where the #include occurs.
When linking multiple .c files that include the same header files, care must be taken to avoid multiple inclusions of the header files (textually inserting a header file more than once). The #ifndef, #define, and #endif preprocessor directives can be used to prevent multiple inclusions.
#ifndef MY_FILE_H
#define MY_FILE_H
/* This code will not be included more than once. */
#endif /* !MY_FILE_H */
I can't understand why I should add the header files if the code is in another file.
The header file contains the declarations for functions defined in the other file, which is necessary for the code that's calling the function to compile correctly.
For instance, suppose I write the following code:
int main(void)
{
double *foo = malloc(sizeof *foo * 10);
if (foo)
{
// do something with foo
free (foo);
}
return 0;
}
malloc is a standard library function that dynamically allocates memory and returns a pointer to it. The return type of malloc is void *, any value of which can be assigned to any other pointer type. free is another standard library function that deallocates memory allocated through malloc, and its return type is void (IOW, no return value).
However, the compiler doesn't automatically know what malloc or free return (or don't return); it needs to see the declarations for both functions in the current scope before it can correctly translate the function calls. Under the C89 standard and earlier, if a function is called without a declaration in scope, the compiler assumes that the function returns int; since int is not compatible with double * (you can't assign one to the other directly without a cast), you'll get an "incompatible assignment" diagnostic. Under C99 and later, implicit declarations aren't allowed at all. Either way the compiler won't translate the code.
I need to add the line
#include <stdlib.h>
which includes the declarations for malloc and free (and a bunch of other stuff) to the beginning of the file.
There are several reasons you don't want to put function definitions (or variable definitions) in header files. Suppose you define function foo in header a.h. You include a.h in files a.c and b.c. Each file will compile okay individually, but when you try to link them together to build a library or executable, you'll get a "multiple definition" error from the linker -- you've wound up creating two separate instances of a function with the same name, which is a no-no. Same goes for variable definitions.
It also doesn't scale well. If you put a bunch of functions in their own header files and include them in one source file, you're translating all those functions in one big glob. Furthermore, if you only change the code in the source file or one header file, you still wind up recompiling everything each time you recompile the .c file. By putting each function in it's own .c file, you can reduce your overall build times by only recompiling the files that need to be recompiled.
I am following the C programming tutorial at http://www.cprogramming.com/tutorial/c/lesson10.html. This particular tutorial teaches file I/O in C; in particular, the fopen command is discussed. At one point, they give the following example (which I think should print the contents of file test.txt):
FILE *fp;
fp=fopen("c:\\test.txt", "w");
fprintf(fp, "Testing...\n");
So, I made a text file called test.txt and saved it in my current, working directory (C:\cygwin\home\Andrew\cprogramming). Then I created a c file in this same directory, and it contains the following code:
#include <stdio.h>
int main()
{
FILE *fp;
fp=open("test.txt","w");
fprintf(fp,"Testing...\n");
}
When I compile this c file (which I've called helloworld2.c) using gcc, I get the following messages:
helloworld2.c: In function `main':
helloworld2.c:40: warning: assignment makes pointer from integer without a cast
Then when I try to run the executable, I get:
Segmentation fault (core dumped)
Do you have any ideas about what I should try next?
Thank you very much for your time.
This is because you use open instead of fopen. Open is from the POSIX standard and returns an (integer) handle; fopen returns the memory address of a FILE structure. You cannot use both in an interchangeable way. As it stands, your code implicitly casts the received integer (likely 4) to a FILE* pointer, making it point to the memory address 4. This segfaults your program when fprintf attempts to access it.
fopen is cross-platform, but open is POSIX-only. You may want to stick to fopen for now.
fopen() returns a pointer to a FILE object while open() returns a file descriptor which is a plain int.
Unless you need low-level functions it's usually better to work with fopen and FILE objects.
I'm guessing this was just an unfortunate typo - open() instead of fopen() - which just happens to work well enough to build a final executable (rather than a deliberate attempt to use open())...
You see warning: assignment makes pointer from integer without a cast because there is no "prototype" - a declaration of the argument and return types - for open() in <stdio.h>.
In the absence of such a prototype, the compiler assumes that such a function exists and returns an int, which your code assigns to the pointer variable fp.
It does in fact link successfully because there is a function called open() in the C library, but it does something different (as others have mentioned). But if (for example) you'd written fpen() instead, things would have gone more obviously wrong - it would have failed at the link stage, as there is no library function of that name.
If you compile with more warnings enabled - e.g. -Wall for GCC - you'll get some more helpful errors:
$ gcc -Wall -o helloworld2 helloworld2.c
helloworld2.c: In function 'main':
helloworld2.c:6: warning: implicit declaration of function 'open'
helloworld2.c:6: warning: assignment makes pointer from integer without a cast
helloworld2.c:8: warning: control reaches end of non-void function
$
The warning: implicit declaration of function 'open' tells you that there is a mismatch between the headers you've included, and the function you're trying to use.
I've started learning some C as a hobby and have blindly used FILE as a declaration for file pointers for quite some time, and I've been wondering. Is this a keyword or special data type for C to handle files with? Does it contain a stream to the file within and other data? Why is it defined as a pointer?
An example to show what I mean to make it a little more clear:
FILE* fp; //<-- this
fp = fopen("datum.txt", "r");
while(!feof(fp)) {
// etc.
}
is this a keyword or special data type for C to handle files with?
What you are refering to is a typedef'd structure used by the standard io library to hold the appropriate data for use of fopen, and its family of functions.
Why is it defined as a pointer?
With a pointer to a struct, you can then pass it as a parameter to a function. This is for example what fgets or fgetc will accept, in the form of function(FILE* fp)
The fopen function will return a pointer to a newly created FILE struct, assigning this new pointer to your unused one will cause them to point to the same thing.
Does it contain a stream to the file within and other data?
The structure definition seems a little more illusive than its description. This is directly taken from my stdio.h, from MinGW32 5.1.4
typedef struct _iobuf
{
char* _ptr;
int _cnt;
char* _base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char* _tmpfname;
} FILE;
Which includes the lovely comment before it:
Some believe that nobody in their right mind should make use of the
internals of this structure.
The contents of this structure appear to change greatly on other implementations, the glibc sources usually have some form of commenting but their structure for this is burried under a lot of code.
It would make sense to heed the aforementioned warning and just not worry what it does. :)
FILE is an identifier used as a typedef name, usually for a struct.
The stdio library usually has something like
typedef struct {
...
} FILE;
somewhere. All stdio functions dealing with FILE pointers know the contens of ... and can access the structure members. The C programmers must use functions like fopen, feof, ferror, ungetc etc to create and operate on FILE structures. Such types are called opaque (i.e. you can´t peek inside them but must use accessor functions).
Why is it defined as a pointer?
It isn't. It's a struct to which your code declares a pointer. Note the asterisk in your
FILE* fp;
which is another example of why the asterisk should go with the variable identifier, not the type name:
FILE *fp;
It's not a keyword, it's a data type defined in the ANSI C standard to operate with files. It usually points to an internal structure that describes the file and its current state to the library functions.
It's a special data type. It contains a file handle as well as various flags used internally by the various stdio calls. You'll never need to actually know what's in it, just that it's a data type that you can pass around.
http://www.cplusplus.com/reference/clibrary/cstdio/FILE/
However if you're interested, here's what it looks like:
http://en.allexperts.com/q/C-1587/2008/5/FILE-Structure.htm