473,785 Members | 2,738 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

fscanf reading lines

I am trying to use fscanf to read my test file. In my test file i
sometimes have blank lines.
When I try to read using the following format.

fscanf(fp,"%[^\n]\n",temp_str) ;

If there is any blank line it reads contents from the next line. How do
I read blank into my variable if the line is blank.

Example

Line Number Input
1 Hi
2
3 Smile

In the above scenario if I try to read line number 2 where it is blank
it reads "Smile" into my temp_sttring variable. How do I ensure if
there is a blank line my variable also ends up blank.

Mar 8 '06 #1
7 27769
bh**********@gm ail.com said:
When I try to read using the following format.

fscanf(fp,"%[^\n]\n",temp_str) ;

If there is any blank line [fscanf] reads contents from the next line.
How do I read blank into my variable if the line is blank.


Easy. Don't use fscanf.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Mar 8 '06 #2
Hello,

when you are using fscanf(fp,"%[^\n]\n",temp_str) ; you are saying that
the token you wish to not parse is '\n'. Since the blank line is
uniquely composed of '\n', then it skips that line and goes to the
next. Check the return value of fscanf to see how many values were
read, which will tell you if there was a blank line or not.
Joel P.

Mar 8 '06 #3
Hi,
what would be the best possible solution in this scenario. i
tried using fgets but it has another problem.
if I want to read something like
Line No Input
1 SMILE

fgets(temp_str, sizeof(temp_str ),fp);

Then in my variable temp_str it contains the value as "SMILE
".

There are some additional characters appended to my variable.

I want only the string "SMILE" come into the variable temp-str.

Please help me on this.

Mar 8 '06 #4
bh**********@gm ail.com writes:
what would be the best possible solution in this scenario. i
tried using fgets but it has another problem.
if I want to read something like
Line No Input
1 SMILE

fgets(temp_str, sizeof(temp_str ),fp);

Then in my variable temp_str it contains the value as "SMILE
".

There are some additional characters appended to my variable.

I want only the string "SMILE" come into the variable temp-str.


You'll have to be much clearer about what you're doing.

Are you saying that line 1 of your input file contains only the string
"SMILE" (followed by a new-line) and nothing else?

Show us a complete compilable program that illustrates the problem
you're having.

(And read <http://cfaj.freeshell. org/google/> *before* you post
another followup.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 8 '06 #5
bh**********@gm ail.com wrote:

I am trying to use fscanf to read my test file. In my test file i
sometimes have blank lines.
When I try to read using the following format.

fscanf(fp,"%[^\n]\n",temp_str) ;

If there is any blank line it reads contents from the next line.
How do
I read blank into my variable if the line is blank.
rc = fscanf(fp, "%[^\n]", temp_str);
if (!feof(fp)) {
getc(fp);
}
if (rc == 0) {
*line = '\0';
}
Example

Line Number Input
1 Hi
2
3 Smile

In the above scenario if I try to read line number 2 where it is blank
it reads "Smile" into my temp_sttring variable. How do I ensure if
there is a blank line my variable also ends up blank.


/* BEGIN type_.c */
/*
** This program uses fscanf
** to read lines of text files.
*/
#include <stdio.h>
#include <stdlib.h>

#define ARGV_0 type_
#define str(s) # s
#define xstr(s) str(s)

unsigned long max_line_len(FI LE *fd);

int main(int argc, char *argv[])
{
int rc;
FILE *fd;
char *line;
unsigned long length;
unsigned long line_length;

if (argc > 1) {
line_length = 1;
line = malloc(line_len gth + 1);
if (line == NULL) {
fprintf(stderr, "line_lengt h is %lu\n", line_length);
exit(EXIT_FAILU RE);
}
while (*++argv != NULL) {
fd = fopen(*argv, "r");
if (fd != NULL) {
length = max_line_len(fd );
if (length > line_length) {
line_length = length;
free(line);
line = malloc(line_len gth + 1);
if (line == NULL) {
fprintf(stderr,
"line_lengt h is %lu\n", line_length);
exit(EXIT_FAILU RE);
}
}
do {
rc = fscanf(fd, "%[^\n]", line);
if (!feof(fd)) {
getc(fd);
}
switch (rc) {
case 0:
*line = '\0';
case 1:
puts(line);
default:
break;
}
} while (rc != EOF);
fclose(fd);
} else {
fprintf(stderr,
"\nfopen() problem with \"%s\"\n", *argv);
break;
}
}
free(line);
} else {
puts(
"Usage:\n>" xstr(ARGV_0)
" <FILE_0.txt> <FILE_1.txt> <FILE_2.txt> ...\n"
);
}
return 0;
}

unsigned long max_line_len(FI LE *fd)
{
unsigned long count, max;
int rc;

count = max = 0;
rc = getc(fd);
while (rc != EOF) {
if (rc == '\n') {
if (count > max) {
max = count;
}
count = 0;
} else {
++count;
}
rc = getc(fd);
}
rewind(fd);
return max;
}

/* END type_.c */
--
pete
Mar 8 '06 #6
pete wrote:
line = malloc(line_len gth + 1); rc = fscanf(fd, "%[^\n]", line);
if (!feof(fd)) {
getc(fd);
} unsigned long max_line_len(FI LE *fd)
{
rewind(fd);
}


If you don't want to go through the file twice,
and don't mind truncating long lines:

#define LENGTH 80

#define str(x) # x
#define xstr(x) str(x)

line_length = LENGTH;
line = malloc(line_len gth + 1);

rc = fscanf(fd, "%" xstr(LENGTH) "[^\n]%*[^\n]", line);
if (!feof(fd)) {
getc(fd);
}

--
pete
Mar 8 '06 #7

<bh**********@g mail.com> wrote in message
news:11******** **************@ j52g2000cwj.goo glegroups.com.. .
I am trying to use fscanf to read my test file. In my test file i
sometimes have blank lines.
When I try to read using the following format.

fscanf(fp,"%[^\n]\n",temp_str) ;

If there is any blank line it reads contents from the next line. How do
I read blank into my variable if the line is blank.

Example

Line Number Input
1 Hi
2
3 Smile

In the above scenario if I try to read line number 2 where it is blank
it reads "Smile" into my temp_sttring variable. How do I ensure if
there is a blank line my variable also ends up blank.


If you are trying to read the last blank-delimited string:
1. read the line using fgets
2. (safety check) if last character in buffer is not newline, repeat
3. replace trailing newline with '\0'
4. use ptr=strrchr(tex t, ' ') to find the last blank
5. if ptr==null the entire string is what you want
6. if ptr != null, ++ptr points to the beginning of the desired string
--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project

Mar 8 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6736
by: Benedicte | last post by:
Hi, I'm getting some problems when using fscanf to read a file. This is a piece of the program code: main () { /*** Variable declaration ***/ FILE *vpfile; /*** Data file ***/
4
3061
by: Psibur | last post by:
Hello, trying to get back into c and was having issue with reading a simple text file with an aribtrary # of lines with 3 int's per line, with the eventual purpose of putting each int into an element of an array (eventually will be other things, but I'm sticking to int's for now). I.e.: 0 1 1 1 1 1 2 1 1 etc... The problem is it'll read and print all but the last line. Is there
7
5458
by: Thomas Sourmail | last post by:
Hi, I hope I am missing something simple, but.. here is my problem: I need my program to check the last column of a file, as in : a b c d target ref 0 0 0 0 1 a 1 0 0 0 1.5 b 2 0 0 0 2 c
7
2829
by: Kay | last post by:
1) If i want to read data from a txt file, eg John; 23; a Mary; 16; i How can I read the above data stopping reading b4 each semi-colon and save it in three different variables ? 2) If I enter a number, can I use to call a particular node ? eg enter a number: 3 calling node of number 3 is it possible ?
1
2215
by: siliconwafer | last post by:
Hi All, here is one code: int main() { FILE*fp; unsigned long a; fp = fopen("my_file.txt","w+"); a = 24; fprintf(fp,"%ld",a); while(fscanf(fp,"%ld",&a) == 1) {
4
4234
by: John | last post by:
I need to read data from the file like the following with name and score, but some line may only has name without score: joe 100 amy 80 may Here's my code, but it couldn't read the line with "may" because there is no score. Anyone knows what is the workaround to this problem?
37
4981
by: PeterOut | last post by:
I am using MS Visual C++ 6.0 on Windows XP 5.1 (SP2). I am not sure if this is a C, C++ or MS issue but fscanf has been randomly hanging on me. I make the call hundreds, if not thousands, of times but it hangs in different places with the same data. The offending code follows. ReadFile(char *csFileName) { float fFloat1, fFloat2;
10
3671
by: rsk | last post by:
Hi Friends, I have written a code which suppose to read all the numbers from a hex file,But to my surprise the code is skiping every alternate value.Don't know why? Can you please help me in solving this problem. The code is as follows;
5
2315
by: a | last post by:
After reading FAQ comp.lang.c section 12 and googling again, still there is no threads talking about reading a series of numbers. The input files, somehow structured, is exemplified below: <presence/absence of n space/tab on the first n lines> 12 <presence/absence of n space/tab here>0<presence/absence of n space/tab here>90 10 23 43 0 0 0 0 0 0 0 90 0 0 0 0 88 0 0 0 ...
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10319
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9947
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6737
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5380
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.