Author : Tom Torfs
Page : << Previous 12 Next >>
like this:
void swapintegers(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
And in the calling code:
swapintegers(&myvariable, &yourvariable);
10.5. Example: using command line parameters
/* prog10-3.c: command line arguments */
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
printf("There are %d command line arguments\n", argc);
for (i=0; i < argc; i++)
{
printf("Command line argument number %d = %s\n", i, argv[i]);
}
return 0;
}
The output on my system is, provided I invoke the program as "prog11 test 123": (but this may be entirely different on yours):
There are 3 command line arguments
Commandline argument number 0 = C:\CINTRO\PROG11.EXE
Commandline argument number 1 = test
Commandline argument number 2 = 123
The first thing that stands out is the other definition of main():
int main(int argc, char *argv[])
{
}
The first parameter (argc) is the number of command line arguments, and the second parameter (argv) is an array (because of the []) of pointers (because of the *) to char. So argv[indexnumber] is a pointer to char, which in this case points to a string (array of char). Strings are often passed as pointers to char, because just using the arrayname of the string will give you the address of the array as a pointer to char. This does not mean that strings (arrays of char) and pointers to char are the same, just that in some cases they have equivalent behaviour. This may be a bit confusing, but it is something you'll soon get familiar with.
On most systems (not all!) argc is usually at least 1. If that is the case argv[0] is either an empty string or the filename (with or without the full path) of the executable. If argc is at least 2 there are command line arguments. In that case argv[1] is the first command line argument, argv[2] the second one, etc. until argv[argc-1].
printf("There are %d command line arguments\n", argc);
This line simply prints out the number of arguments. As noted above, be aware that even if argc is 1 that still means there are no command line arguments other than the program name, argv[0], if supported. So if for example your program requires 1 command line argument, you should check for argc==2.
int i;
/* ... */
for (i=0; i < argc; i++)
{
printf("Commandline argument number %d = %s\n", i, argv[i]);
}
This for loop goes through the argv array from index 0 to argc-1 using the integer variable i as counter. For every command line argument the number and content is printed. Notice that if argc==0 the loop is never executed.
Note: as said above, the definition:
char *argv[]
Defines an array of pointers to char. Because an array parameter is always passed as pointer, in this case this is equivalent to:
char **argv
Which is a pointer to a pointer to char, that can be used as an array of pointers to char (see 12. Dynamic memory allocation for another example of this handy similarity between pointers and arrays).
These sort of definitions and declarations can soon become confusing, especially when pointers to functions etc. start coming into play. A handy rule to understand complex definitions is the so-called right-to-left rule. You can read all about it in rtlftrul.txt in the Snippets collection (see 17.2. Other interesting online C-related material).
11. Using files
11.1. The fileio program
/* prog11-1.c: fileio */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char s[20];
char *p;
FILE *f;
strcpy(s,"file I/O test!");
printf("%s\n",s);
f = fopen("testfile","w");
if (f==NULL)
{
printf("Error: unable to open testfile for writing\n");
return EXIT_FAILURE;
}
fputs(s,f);
fclose(f);
strcpy(s,"overwritten");
printf("%s\n",s);
f = fopen("testfile","r");
if (f==NULL)
{
printf("Error: unable to open testfile for reading\n");
return EXIT_FAILURE;
}
if (fgets(s, sizeof s, f) != NULL)
{
p = strchr(s,'\n');
if (p!=NULL)
*p = '\0';
printf("%s\n",s);
}
fclose(f);
if (remove("testfile") != 0)
{
printf("Error: unable to remove testfile\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
This program's output should be:
file I/O test!
overwritten
file I/O test!
11.2. Using disk files
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
We need stdio.h not only for printf(), but also because it declares all file I/O functions that we're going to use here.
We need stdlib.h because we're no longer going to simply use return 0; but we're going to return a success/failure status to the operating system and EXIT_SUCCESS and EXIT_FAILURE are defined in stdlib.h (see 2.5. return).
We need string.h because we're going to work with strings, and need the functions strcpy() and strchr().
char s[20];
char *p;
FILE *f;
The first line defines an array of 20 characters, which we'll use to hold a string of upto 19 characters plus 0 terminator byte.
The second line defines a pointer to char that will be used to store the return value of the strchr() function (see below).
The third line defines a pointer to FILE. Such a pointer to FILE is used by almost all the file I/O programs in C. It is also referred to as a stream. This pointer is the only form the FILE type is used as; you may not define variables of type FILE by themselves.
strcpy(s,"file I/O test!");
printf("%s\n",s);
The text "file I/O test!" is copied into s and printed.
f = fopen("testfile","w");
OK, this is new. The fopen() function opens a file and returns a pointer to FILE that will be used by all other file I/O functions you'll use to access this file.
The first parameter to fopen() is the filename (a string). The second parameter is also a string, and can be any of the following:
"w" open for writing (existing file will be overwritten)
"r" open for reading (file must already exist)
"a" open for appending (file may or may not exist)
"w+" open for writing and reading (existing file will be overwritten)
"r+" open for reading and updating (file must already exist)
"a+" open for appending and reading (file may or may not exist)
Append mode ("a") will cause all writes to go to the end of the file, regardless of any calls to fseek(). By default the files will be opened in text mode (which means that '\n' will be translated to your operating system's end-of-line indicator, other sorts of translations may be performed, EOF characters may be specially treated etc.). For binary files (files that must appear on disk exactly as you write to them) you should add a "b" after the above strings. [*]
[*] Some compilers also support a "t" for text files, but since this is non-standard and not required (since it is the default) you shouldn't use it.
if (f==NULL)
{
printf("Error: unable to open testfile for writing\n");
return EXIT_FAILURE;
}
As mentioned above, fopen() returns a pointer to FILE that will be used by the other file I/O functions. However, in case an error occurred (fopen() was unable to open the file for some reason) the returned pointer to file will be NULL (the invalid pointer value, see 10.4. Addresses and pointers).
If that happens, this program prints an error message and returns to the operating system with the EXIT_FAILURE status.
fputs(s,f);
The fputs() function writes a string to a file. It is similar to the puts() function (see 2.4. Functions and types), but there are two differences:
- a second parameter is taken: a pointer to FILE corresponding to the file the string should be written to
- unlike puts(), fputs() does not automatically append a '\n' character
fclose(f);
The fclose() function closes the file associated with a pointer to FILE, which has previously been opened by fopen(). After the fclose() you may not use the pointer to FILE as a parameter to any of the file I/O functions anymore (until a new file handle returned by e.g. fopen() has been stored in it, of course).
strcpy(s,"overwritten");
printf("%s\n",s);
This code copies a new text into s, thereby overwriting the previous text, and prints this new text.
f =
Page : << Previous 12 Next >>