Archived

This topic is now archived and is closed to further replies.

joseph drake

Maybe you consider funny asking this?

Recommended Posts

joseph drake    122
Hi there, Could anybody help me with making a string from a char array in C, for instance, when reading from a file, I want to make a whole line a string except for a linefeed(10) ‘char’. Thanks

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
If you read from a file, you can already load it as a string.

fgets(char*, int, FILE*);
so:
char* string;
FILE* file = open(...);
fgets(string, 1024, file); // It doesn''t have to be 1024, but if it''s too small, you won''t get the full line (it stops on return char)

or using fstream:
ifstream file;
char* string;
file.open(...);
file.getline(string, 1024) // you can change what is the end of line caracter, default is \n

hope that helps

Share this post


Link to post
Share on other sites
hellz    356
quote:
Original post by Anonymous Poster
If you read from a file, you can already load it as a string.

fgets(char*, int, FILE*);
so:
char* string;
FILE* file = open(...);
fgets(string, 1024, file); // It doesn''t have to be 1024, but if it''s too small, you won''t get the full line (it stops on return char)



You''ve not initialised the string pointer, to point anywhere. When you attempt to read information from a file, that pointer could be pointing anywhere, so you''re attempting to overwrite any possible block of memory. This = VERY bad. Incidentally, you''re doing the very same with your C++ example.

Try something like this isntead:


#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *fp; /* Declare a file pointer. */
char string[1024]; /* Create a large string buffer. */

/* Attempt to open a file for reading ("r"). If it fails,
** print an error message to the standard error stream (stderr)
** and terminate the program signalling that it was unsuccessful.
*/
if ((fp = fopen("something.txt", "r")) == NULL)
{
fprintf(stderr, "%s", "Cannot open file for reading.\n");
exit(EXIT_FAILURE);
}

/* Read a string from the file. */
fgets(string, 1024, fp);

/* Print the contents read in from the file. */
printf("Contents from first line of file: %s", string);

/* Close the file. */
fclose(fp);

return 0;
}


It''s just a simple example. Using dynamically allocated memory using pointers, with files is slightly more difficult, but to keep it simple, the above code will do what you''re looking for.

--hellz

Share this post


Link to post
Share on other sites