-1

I am trying to read some commands which should be passed to my program from a file. The commands are on different lines, so I guess this means that they are separated by \n character. This is my command reading section:

FILE *fop;
char command[50];
fopen("mbr.op", "r");
while(!feof(fop))
{ 
    fscanf(fop,"%s[^\n]", command);
    printf("%s\n", command);
}
fclose(fop);

This prints some words that are in the file, but not all, and not in the expected order. How could I change this code to achieve the desired result?

Polb
  • 640
  • 2
  • 8
  • 21
  • `while(!feof(fp))` and casting the result of `malloc` are two plagues descended upon the community of people learning C... – user4520 Dec 26 '15 at 14:17

2 Answers2

2

You open your file incorrectly (it returns a FILE pointer which is associated with the opened file), fopen should be used as this -

fop=fopen("mbr.op", "r");

And while(!feof(fop)) should not be used .

You can write your loop as follows -

while(fscanf(fop,"%[^\n]%*c", command)==1)
{  
  printf("%s\n", command);
}

Note - Also check if file was opened successfully.

Community
  • 1
  • 1
ameyCU
  • 16,489
  • 2
  • 26
  • 41
  • `fgets()` will save newline character read to the buffer, so you will get two newline character after each line in your code using `fgets()`. – MikeCAT Dec 26 '15 at 14:10
  • @MikeCAT Hmm yes mention in question that separated by `'\n` , didn't paid attention . `fgets` will be inappropriate. – ameyCU Dec 26 '15 at 14:11
  • 1
    Your code using `fscanf()` won't work. It will [read only first line](http://melpon.org/wandbox/permlink/i2bZCuqV89I0SCTd). – MikeCAT Dec 26 '15 at 14:13
  • @MikeCAT new line character has to be taken care of . – ameyCU Dec 26 '15 at 14:15
1
FILE *fop;
char command[50];
fop = fopen("mbr.op", "r"); /* get the file pointer */
if (fop == NULL) exit(1); /* check if the file successfully opened */
while(fscanf(fop,"%49[^\n]%*c", command) == 1) /* see notes after this code */
{ 
    printf("%s\n", command);
}
fclose(fop);

Notes on the usage of fscanf():

  • They say using feof() is not good.
  • Yon won't need the s.
  • Specify the maximum length to read to avoid buffer overflow.
  • Added %*c to have it skip the newline character.

This code above won't work well if there are blank lines. I think using fgets() is better to read lines.

FILE *fop;
char command[51]; /* added 1 byte to store the newline character */
fop = fopen("mbr.op", "r");
if (fop == NULL) exit(1);
while(fgets(command, sizeof(command), fop))
{
    /* remove the newline character */
    char* p;
    for(p = command; *p != '\0' && *p != '\n'; p++);
    *p = '\0';
    /* print what is read */
    printf("%s\n", command);
}
fclose(fop);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70