<jo******@hotmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
Hello all, new user to c programming and am having difficulty with a
little program I am trying to write. Basically what I have is a file
which contains a list of words i.e:
tst.txt:
customer
customers
data
deactivate
deactivated
department
department
dept.
etc....
I want to read in each word from the file Individually, and assign each
individual word to an individual element in an array.
the code I have so far is:
#include <stdio.h>
#include <string.h>
main()
{
int c;
FILE *in_file;
FILE *out_file;
FILE *out;
in_file = fopen ("thes1.txt", "r");
if( in_file == NULL )
printf("Cannot open %s for reading.\n");
else
out_file = fopen ("tst.txt", "w");
if( out_file == NULL )
printf("Can't open %s for writing.\n");
else {
while( (c = getc( in_file)) != EOF )
{
putc (c, out_file);
}
putc (c, out_file); /* copy EOF */
printf("File has been copied.\n");
}
fclose (in_file);
fclose (out_file);
out = fopen("tst.txt","r");
int zz=0;
char key2[20];
while(!feof(out))
{
fgets(key2,20,out);
printf("%s\n",key2);
}
}
this code will get each word Individually, but so far I have not been
able to assign words to elements in an array, continiously getting
errors about invalid conversions from char*. Any help would be greatly
appreciated.
Kind Regards
I'm not exactly sure what your trying to do but if you are attempting to
assign to an array directly you cannot do it in C.
C does not have strings, it has arrays of characters terminated with a null
character which is actually binary 0 represented as '\0'. However most
people call them strings. There are many string functions to manipulate
character arrays, they all work on the idea of
1. The name of the array is the address of the array.
2. The array will be terminated with a binary 0 to indicate the end of the
text.
Or there are a group of 'mem' functions to work with data. Take a look at
the strcpy/strncpy and memcpy functions. Make sure you understand how they
work and differences between them.
char xxx[10] = "DAVE"; OK at initialisation
xxx = "PAUL" is invalid - xxx is address of array,
"PAUL" is constant string.
xxx[0] = 'P'; OK;
xxx[1] = "AUL"; Invalid, xxx[1] is a character, "AUL" is a
string
On a separate note, you need to take a look at your error checking when
opening the two files at the top.
in_file = fopen ("thes1.txt", "r");
if( in_file == NULL )
printf("Cannot open %s for reading.\n");
else
out_file = fopen ("tst.txt", "w");
if( out_file == NULL )
printf("Can't open %s for writing.\n");
Ask yourself - what is going to happen if the fopen of "thes1.txt" fails?
Is out_file going to be NULL? It probably works at at the moment because
"thes1.txt" exists - try renaming or deleting it and run the program again.
HTH, Paul