In plain ANSI C, what is the neatest way to grab a string of a specified length (specified elsewhere in the programme) and assign it to an array/pointer? So I want to grab the next 60 chars from a file and place in an array to work with.
moonfish
05-22-02, 11:13 PM
//file demo by staightp@uci.edu
#include < stdio.h >
#include < malloc.h >
int main (void)
{
FILE *the_file;
char* block;
int x;
x=60;
printf("%s",NULL!=(the_file=fopen("file.txt", "r"))?
fgets(block=(char*) malloc(sizeof(char)*x), x ,the_file)
:"couldn't open the file\n");
if(the_file){fclose(the_file);delete block;}
return 0;
}
/*
fopen(char *name,char *option)
it takes the name of the file and an option, and returns a FILE pointer.
- the name can be any directory tree path. Even something like /mount/floppy/file, Windows won't let me specify A:/file :(
- it returns NULL if it can't open.
- the options are read wright or append; following this table
open stream for truncate create starting
mode read write file file position
---- ---- ----- ---- ---- --------
"r" y n n n beginning
"r+" y y n n beginning
"w" n y y y beginning
"w+" y y y y beginning
"a" n y n y end-of-file
"a+" y y n y end-of-file
fgets(char *out, int length, FILE* in)
it takes a char pointer to put the data, the number of char to read, and a FILE pointer
it returns a copy of the char pointer you gave it
- if it reads a new line '\n' or end of file '\0' it will stop
- it puts a \0 on the end of whatever it read
Background
When we access a file the OS needs to read the secondary memory device, usually the hard disk.
It's all done internally with fopen and fclose, so you needn't worry about it too much.
Just remember it's generally a couple thousand times slower than any normal line of code.
*/
moonfish
05-22-02, 11:27 PM
so the cool line is:
printf("%s",NULL!=(the_file=fopen("file.txt","r"))?fgets(block=(char*)malloc(sizeof(char)*x),x,the _file):"couldn't open the file\n");
but the form keeps putting returns in my coad so I split it into 3