• 0

[C] File input and strcmp.


Question

Hello,

I am reading from a file of this format :

ID 1

name

name

name

etc.

ID 2

name

name

name

etc.

I am using fscanf to read (like this fscanf(file,"%s\n",data)), as far as I am aware fscanf will skip special characters right? So how can I understand when I get ID 1? I think it doesn't take the blank space....

Is there any other way besides reading char by char?

Thanks a lot

Link to comment
https://www.neowin.net/forum/topic/778574-c-file-input-and-strcmp/
Share on other sites

3 answers to this question

Recommended Posts

  • 0

Yes you're right. fscanf() will read whitespace and ignore it. You could maybe use something like fgets() as it will read the whole line in up to a \n

Then you can just use strcmp() to find out what the line is. Ensure you create a buffer of adequate size, however given the file you're reading in, it won't have to be that large at all.

  • 0
  ViZioN said:
Yes you're right. fscanf() will read whitespace and ignore it. You could maybe use something like fgets() as it will read the whole line in up to a \n

Then you can just use strcmp() to find out what the line is.

Cool thanks, I will try it out and report back. :)

EDIT : Ok, but if I use fgets and I reach the EOF, it will store EOF in my string variable??

How can I compare my string to an EOF?

Part of my code is like this : if (fgets(data,255,fin) != EOF

The above probably won't work though:P - would it work if I cast fgets?

Edited by gianpan
  • 0

It won't store the EOF within the string, but it will however store the \n within the string. If the EOF is encountered, fgets() returns a NULL pointer so I just checked for that.

Something like this may work:

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

int main()
{
	FILE *pFile = NULL;
	char string[100];

	pFile = fopen("text.txt", "r+");

	if(!pFile){
		printf("File cannot be opened.\n");
		return 0;
	}

	while( fgets(string, 99, pFile) != NULL){
		if(strcmp(string, "ID 1\n") == 0){
			printf("ID 1 found\n");
		}else if(strcmp(string, "ID 2\n") == 0){
			printf("ID 2 found\n");
		}
	}

	printf("\nEOF reached\n");
	getchar();

	return 0;
}

There is more information here - http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

I tested it using the file

ID 1
ID 2
ID 1

Note there is a blank new line at the end of the file. This is to cope with fgets reading the \n.

You can just then modify so that once you've read an ID you can read the names. You may also want to read the file more than once so you can figure how much memory you will need to allocate to store all the names. This allows you to cope with different sizes of text file.

Hope this helps.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.