I want to scan a file and skip a line of text before reading. I tried:
fscanf(pointer,"\n",&(*struct).test[i][j]);
But this syntax simply starts from the first line.
I was able to skip lines with scanf with the following instruction:
fscanf(config_file, "%*[^\n]\n");
The format string matches a line containing any character including spaces. The * in the format string means we are not interested in saving the line, but just in incrementing the file position.
Format string explanation:
% is the character which each scanf format string starts with;
* indicates to not put the found pattern anywhere (typically you save pattern found into parameters after the format string, in this case the parameter is NULL);
[^\n] means any character except newline;
\n means newline;
so the [^\n]\n means a full text line ending with newline.
Reference here.
fgets will get one line, and set the file pointer starting at the next line. Then, you can start reading what you wish after that first line.
char buffer[100];
fgets(buffer, 100, pointer);
It works as long as your first line is less than 100 characters long. Otherwise, you must check and loop.
It's not clear what are you trying to store your data into so it's not easy to guess an answer, by the way you could just skip bytes until you go over a \n:
FILE *in = fopen("file.txt", "r");
Then you can either skip a whole line with fgets but it is unsafe (because you will need to estimate the length of the line a priori), otherwise use fgetc:
char c;
do {
c = fgetc(in);
} while (c != '\n');
Finally you should have format specifiers inside your fscanf to actually parse data, like
fscanf(in, "%f", floatVariable);
you can refer here for specifiers.
fgets would work here.
#define MAX_LINE_LENGTH 80
char buf[MAX_LINE_LENGTH];
/* skip the first line (pFile is the pointer to your file handle): */
fgets(buf, MAX_LINE_LENGTH, pFile);
/* now you can read the rest of your formatted lines */
Related
I'm trying to read a line using the following code:
while(fscanf(f, "%[^\n\r]s", cLine) != EOF )
{
/* do something with cLine */
}
But somehow I get only the first line every time. Is this a bad way to read a line? What should I fix to make it work as expected?
It's almost always a bad idea to use the fscanf() function as it can leave your file pointer in an unknown location on failure.
I prefer to use fgets() to get each line in and then sscanf() that. You can then continue to examine the line read in as you see fit. Something like:
#define LINESZ 1024
char buff[LINESZ];
FILE *fin = fopen ("infile.txt", "r");
if (fin != NULL) {
while (fgets (buff, LINESZ, fin)) {
/* Process buff here. */
}
fclose (fin);
}
fgets() appears to be what you're trying to do, reading in a string until you encounter a newline character.
If you want read a file line by line (Here, line separator == '\n') just make that:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
FILE *fp;
char *buffer;
int ret;
// Open a file ("test.txt")
if ((fp = fopen("test.txt", "r")) == NULL) {
fprintf(stdout, "Error: Can't open file !\n");
return -1;
}
// Alloc buffer size (Set your max line size)
buffer = malloc(sizeof(char) * 4096);
while(!feof(fp))
{
// Clean buffer
memset(buffer, 0, 4096);
// Read a line
ret = fscanf(fp, "%4095[^\n]\n", buffer);
if (ret != EOF) {
// Print line
fprintf(stdout, "%s\n", buffer);
}
}
// Free buffer
free(buffer);
// Close file
fclose(fp);
return 0;
}
Enjoy :)
If you try while( fscanf( f, "%27[^\n\r]", cLine ) == 1 ) you might have a little more luck. The three changes from your original:
length-limit what gets read in - I've used 27 here as an example, and unfortunately the scanf() family require the field width literally in the format string and can't use the * mechanism that the printf() can for passing the value in
get rid of the s in the format string - %[ is the format specifier for "all characters matching or not matching a set", and the set is terminated by a ] on its own
compare the return value against the number of conversions you expect to happen (and for ease of management, ensure that number is 1)
That said, you'll get the same result with less pain by using fgets() to read in as much of a line as will fit in your buffer.
Using fscanf to read/tokenise a file always results in fragile code or pain and suffering. Reading a line, and tokenising or scanning that line is safe, and effective. It needs more lines of code - which means it takes longer to THINK about what you want to do (and you need to handle a finite input buffer size) - but after that life just stinks less.
Don't fight fscanf. Just don't use it. Ever.
It looks to me like you're trying to use regex operators in your fscanf string. The string [^\n\r] doesn't mean anything to fscanf, which is why your code doesn't work as expected.
Furthermore, fscanf() doesn't return EOF if the item doesn't match. Rather, it returns an integer that indicates the number of matches--which in your case is probably zero. EOF is only returned at the end of the stream or in case of an error. So what's happening in your case is that the first call to fscanf() reads all the way to the end of the file looking for a matching string, then returns 0 to let you know that no match was found. The second call then returns EOF because the entire file has been read.
Finally, note that the %s scanf format operator only captures to the next whitespace character, so you don't need to exclude \n or \r in any case.
Consult the fscanf documentation for more information: http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/
Your loop has several issues. You wrote:
while( fscanf( f, "%[^\n\r]s", cLine ) != EOF )
/* do something */;
Some things to consider:
fscanf() returns the number of items stored. It can return EOF if it reads past the end of file or if the file handle has an error. You need to distinguish a valid return of zero in which case there is no new content in the buffer cLine from a successfully read.
You do a have a problem when a failure to match occurs because it is difficult to predict where the file handle is now pointing in the stream. This makes recovery from a failed match harder to do than might be expected.
The pattern you wrote probably doesn't do what you intended. It is matching any number of characters that are not CR or LF, and then expecting to find a literal s.
You haven't protected your buffer from an overflow. Any number of characters may be read from the file and written to the buffer, regardless of the size allocated to that buffer. This is an unfortunately common error, that in many cases can be exploited by an attacker to run arbitrary code of the attackers choosing.
Unless you specifically requested that f be opened in binary mode, line ending translation will happen in the library and you will generally never see CR characters, and usually not in text files.
You probably want a loop more like the following:
while(fgets(cLine, N_CLINE, f)) {
/* do something */ ;
}
where N_CLINE is the number of bytes available in the buffer starting a cLine.
The fgets() function is a much preferred way to read a line from a file. Its second parameter is the size of the buffer, and it reads up to 1 less than that size bytes from the file into the buffer. It always terminates the buffer with a nul character so that it can be safely passed to other C string functions.
It stops on the first of end of file, newline, or buffer_size-1 bytes read.
It leaves the newline character in the buffer, and that fact allows you to distinguish a single line longer than your buffer from a line shorter than the buffer.
It returns NULL if no bytes were copied due to end of file or an error, and the pointer to the buffer otherwise. You might want to use feof() and/or ferror() to distinguish those cases.
i think the problem with this code is because when you read with %[^\n\r]s, in fact, you reading until reach '\n' or '\r', but you don't reading the '\n' or '\r' also.
So you need to get this character before you read with fscanf again at loop.
Do something like that:
do{
fscanf(f, "%[^\n\r]s", cLine) != EOF
/* Do something here */
}while(fgetc(file) != EOF)
I'm trying to selectively filter a text file by a string which is input to the standard input.
I would like to know why the following code does not work and how to fix it:
void get_filtered_list() {
FILE *f;
f = fopen("presentlist.txt", "r");
printf("Enter the city by which you want to select lines:\n");
char stringToFind[20];
fgets(stringToFind, sizeof(stringToFind), stdin);
char line[160];
while (!feof(f)) {
fgets(line, sizeof(line), f);
if (strstr(line, stringToFind) != NULL) {
printf("%s", line);
}
}
fclose(f);
}
This code above is trying to take a text file, opening that file, then reading the file line by line, and for each line executing the strstr() function with the current line of the file as argument 1 as a string, and the given name of the city as argument 2 as a string.
However what I get as a result is the ENTIRE contents of the file printed (and the last line prints twice, though this is a separate issue and I know the fix to this part).
The C book I'm reading states that the strstr() function is used to find a needle string in a haystack string, so it's the C equivalent of the C++ substr() function.
strstr() takes argument 1 as the haystack and argument 2 as the needle.
I first read in from the standard input into the needle, then line by line I check whether strstr() returns NULL or not (it should return NULL if the needle is not found in the haystack) and if it returns something other than NULL that means it found the substring in the string and it should only print the line THEN.
Instead it prints all of the lines in the file. Why?
If I switch it to f(strstr(line, stringToFind)) instead then it prints absolutely nothing.
Why?
You do not find the string because you did not strip the trailing '\n' from the string read into stringToFind by fgets. Actually, you will find the string if and only if it is the last word on a line.
You can remove the linefeed with this:
#include <string.h>
stringToFind[strcspn(stringToFind, "\n")] = '\0';
There are other ways to strip the linefeed, but be aware that if the last line of the file does not end with a linefeed, there will not be one in the buffer filled by fgets, therefore you cannot just overwrite the last character of the line. For your problem, it would be a good idea to remove all whitespace characters at the beginning and at the end of stringToFind.
Also check this question: Why is “while ( !feof (file) )” always wrong?
Testing the end of file with while (!feof(f)) will catch the end of file too late: fgets will fail and you do not test its return value, so the last line of the file will appear to be handled twice. The correct way to write this loop is this:
while (fgets(line, sizeof(line), f)) {
if (strstr(line, stringToFind) != NULL) {
printf("%s", line);
}
}
Not also that lines longer than 159 characters will be split by fgets and will cause incorrect output if they contain the searched string, especially if the string itself is split.
I'm trying to read a text file line by line and printing the first 17 characters.
FILE *devices;
devices = NULL;
devices = fopen("devices.txt", "r");
char deviceaddr[17];
char addr[17];
char line[1024];
while (fgets(line,1024,devices) != NULL)
{
fscanf(devices,"%s", deviceaddr);
printf("%s\n", deviceaddr);
}
fclose(devices);
the output should be 00:07:80:4C:0E:EEfor the first line but it gives 6.
The while loop is reading a line of text, then the fscanf will read the next set of text (and possibly overrun that buffer incidentally). It seems as if you should just be printing the desired data inside the loop from the buffer line.
For example, suppose there are three lines of text.
00:07:80:4C:0E:EE --> ends up line buffer line
second --> ends up in deviceaddr
third line --> ends up in line (unless the fscanf did not consume newline)
There's no way the output can be "00:07:80:4c:0E:EE", since
that would result in undefined behavior, due to buffer
overrun—the string requires 18 bytes, but you only provide
17. You should never us "%s" in an fscanf without
specifying the length.
And you're calling fscanf on devices after having read
a line from it; if you're reading line by line, you want to use
sscanf on the line you've read.
I am trying to scan a file using fscanf and put the string into an char array of size 20 as follows:
char buf[20];
fscanf(fp, "%s", buf);
The file fp currently contains: 1 + 23.
I am setting a pointer to the first element in buf as follows:
char *p;
p = buf;
Printing buf, printf("%s", buf) yields only 1. Trying to increment p and printing prints out rubbish as well (p++; printf("%c", *p)).
What am I doing wrong with fscanf here? Why isn't it reading the whole string from the file?
fscanf (and related functions) with the format-string "%s" will try to read as many characters as it can without including a whitespace, in this case it will find the first character (1) and store it, then it will hit a space () and therefore stop searching.
If you'd like to read the whole line at once consider using fgets, it is also safer to use since you need to specify the size of your destination buffer as one of it's arguments.
fgets will try to read at maximum length-of-buffer minus 1 characters (last byte is saved for the trailing null-byte), it will stop at either reading that many characters, hitting a new-line or the end of the file.
fgets (buf, 20, fp);
Links to documentation
codecogs.com - scanf, fscanf and related functions - <stdio.h>
codecogs.com - fgets - <stdio.h>
I'm trying to write a function that takes a stream as an argument and reads from that stream and reads in the contents of the file up to the first whitespace as defined by the isspace function, and then uses the strtok function to parse the string. I'm not sure how to start it though with which function to read a line and ignore the whitespace. I know fgetc and getc only read one character at a time, and looking up the fscanf reference, will that work? Or does that only find items in your stream according to the format specifiers %s? Thanks!
To read an entire line at a time, you generally should use fgets. Some care is needed in case a line in the stream is longer than your buffer, the leftover will remain in the stream, which might not be what you want. (If you want to ignore the rest of the line, you can use fgets followed by fscanf as described at http://home.datacomm.ch/t_wolf/tw/c/getting_input.html.)
If you want to read in an entire line without worrying about a buffer size, you may wish to look into Chuck Falconer's ggets function which dynamically allocates a buffer for you (this does mean that you are responsible for freeing it).
C Answer
The fscanf s conversion will match a sequence of non-white-space characters. The input string stops at white space (as defined by isspace) or at the maximum field width, whichever occurs first. Note that there must be enough space in the provided buffer or it may be overflowed by long input.
FILE *fp;
char cstr[128];
fp = fopen("test.txt", "r");
while (!feof(fp))
{
fscanf(fp, "%s", cstr);
...
}
Original C Answer
The fgets function will allow you to read in the file one line at a time, but you will still need to check each character with isspace.
Since isspace may include space, form-feed ('\f'), newline ('\n'), carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v') in its check for white-space characters, your best bet may be to read one character at a time in a loop using the fgetc function. Note that if the integer value returned by fgetc() is stored into a variable of type char and then compared against the integer constant EOF, the comparison may never succeed, because sign-extension of a variable of type char on widening to integer is implementation-defined.
FILE *fp;
int c;
fp = fopen("test.txt", "r");
while ((c = fgetc(fp)) != EOF)
{
if (isspace(c))
{
...
}
else
{
...
}
}
Original C++ Answer
The istream::getline method will allow you to read in one line at a time and optionally specify the delimiter (default is '/n').
Since isspace may include space, form-feed ('\f'), newline ('\n'), carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v') in its check for white-space characters, your best bet may be to read one character at a time in a loop using the istream::get method.
char c;
string str;
ifstream file("test.txt",ios::in);
while (file.get(c))
{
if (isspace((unsigned char)c))
{
...
}
else
{
str.push_back(c);
}
file.peek();
if (file.eof())
{
break;
}
}
Note: Error checking was omitted from the all of the above code for simplicity.
well although getc/fgetc only retrieve 1 character at a time, you can put them into a loop right ?:)