Need help with a function that reads from a text file usins fscanf function.
example say there is 20 stings that are 60 chars long on their own individual line. Does fscanf() read the whole text file or does it read only up to the carriage return. If it doesn't how can you only read the first string in the text file up to the carriage return using fscanf(), i am using C code.

output of text file

hellothereadkdkdkdkd
aldldjfjbualdfljdlfjdfjdl
aldfl;jlfdljflfldjfldjbyhh

my program does not allow to have spaces in between the 60char string,
so i cannot figure how to read the first string in the text because there is a carriage return after every line so it does not look like one massive string. i know that the type File pointer , points to the beginning of the text file but how do you procedd to read in the first string only?????
Please help!!


Hey,

I was reading your message because I was having problems with the same thing. Try this

void read_file(char string[60])
{
  FILE *fp;
  char filename[20];
  printf("File to open: \n", &filename );
  gets(filename);
  fp = fopen(filename, "r");  /* open file for input */

  if (fp)  /* If no error occurred while opening file */
  {           /* input the data from the file. */
    fgets(string, 60, fp); /* read the name from the file */
    string[strlen(string)] = '\0';
    printf("The name read from the file is %s.\n", string );
  }
  else          /* If error occurred, display message. */
  {
    printf("An error occurred while opening the file.\n");
  }
  fclose(fp);  /* close the input file */
}

It worked for me. I had used your code to help me out with my assignment, so I'd thought I'd return the favor.

Thank you! Hopefully that works after some variable changing and restructering.

>>string[strlen(string)] = '\0';

That may or may not work -- if the string does not contain '\n' the above will cut off the last character that was read. fgets() appends the '\n' ONLY if there is one in the stream -- for example if the buffer is filled up before reaching end-of-line or when the last line in the file does not contain '\n'. So the safest way to do it is to check if the last character is '\n'

int len = strlen(string) -1;
if( string[len] == '\n')
   string[len] = '\0';
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.