A small program to read lines from a file:
(Note program has not been testet, not even compiled)
Code:
/*
* needed includes in order to use:
* fopen(), fgets(), fclose() and printf()
*/
#include <stdio.h>
/*
* In order to have a precise line length we're going for everytime
* we define the LINE_SIZE
*/
#define LINE_SIZE 256
/*
* Definition of function beeing used by main(),
* also known as the prototype.
*/
int read_file(char* file_name);
/*
* main() is a function which is invoked with every argument given
* in the program call.
* argc: tells you how many arguments given (including program name)
* argv: an array of char* with the arguments parsed to the program
*/
int main(int argc, char* argv[])
{
int status = 0;
if(argc != 2)
{
printf("Usage: %s <file_name>\n",
argv[0]);
return -1;
{
if(0 != (status = read_file(argv[1]))
printf("Reading of file [%s] failed with status: %d\n",
argv[1], status);
return status;
}
/*
* read_file() is the actual function to open/read and print
* what has been read from the file.
* Depending on where it might fail, it will return an error code
* to which the caller can act apropriate on.
*/
int read_file(char* file_name)
{
FILE* file;
char buffer[LINE_SIZE];
int i = 0;
file = fopen(file_name);
if(!file)
return -1;
while(!feof(file))
{
if(!fgets(buffer, LINE_SIZE, file))
{
fclose(file);
return -2;
}
printf("Line (%d) in file [%s]: %s\n",
++i, file_name, buffer);
}
fclose(file);
return 0;
}
Quote:
|
Another thing whats the format for writing and declaring a function prototype the returns more than one object?
|
In short you can't.
C dosn't allow you to return different types of objects, the function prototype can be declared to return a specific struct, and this can consist of pointers to different objects/structs/types, where the function can either set these to NULL or point to the resulting object.
An ugly way of achieving it, is to have a function which returns a
void* and then later on typecast that to whatever you would use, but that's just insane, since a void* wont tell you what type it intentionaly was.