473,779 Members | 2,078 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

fscanf into an array

Hi, I'm a complete NOOB.
How do I get fscanf to copy into an array? I also need to use malloc,
but where do I put it in my file?
_______________ _______________ _______________ __________
FILE *ifp;

char c;
int y = 0;

txtFile = (char *) malloc(FILELENG TH * sizeof(char)) ;

printf ("Enter the name of the file to analyze : ");
gets (filename);
printf ("\n");
ifp = fopen(filename, "r");

if (ifp == NULL)
{
fprintf (stderr, "Error opening file\n");
exit (-2);
}
while(fscanf (ifp, "%c", &c) != EOF)
{
txtFile[y] = c;
y++;
}

Nov 5 '06 #1
3 6694
to********@gmai l.com said:
How do I get fscanf to copy into an array?
One element at a time.
I also need to use malloc,
but where do I put it in my file?
At the point where you first need the memory. Be sure to #include <stdlib.h>
for the malloc prototype.
FILE *ifp;

char c;
int y = 0;

txtFile = (char *) malloc(FILELENG TH * sizeof(char)) ;
txtFile = malloc(FILELENG TH * sizeof *txtfile);
if(txtFile != NULL)
{
>
printf ("Enter the name of the file to analyze : ");
gets (filename);
Don't use gets. It's a buffer overflow waiting to happen. Instead, use
fgets, find the newline using strchr, and overwrite it with '\0' if it's
found. (If it's not found, you probably don't want to accept the filename
anyway.)
printf ("\n");
ifp = fopen(filename, "r");

if (ifp == NULL)
{
fprintf (stderr, "Error opening file\n");
exit (-2);
}
while(fscanf (ifp, "%c", &c) != EOF)
I recommend == 1 rather than != EOF. fscanf returns the number of fields
successfully converted, and you're expecting one field, so that's what you
should test for.
{
txtFile[y] = c;
y++;
}
This is fine provided y never equals or exceeds the array bound. But, to
answer your question(!), you can instead do this:

y = 0;
while(y < FILELENGTH && fscanf(ifp, "%c", &txtFile[0]) == 1)
{
y++;
}

if(y == FILELENGTH)
{
you ran out of buffer, but at least no harm was done.
}

If you plan to use txtFile as a string, don't forget to null-terminate it,
which entails leaving space for a null terminator:

y = 0;
while(y < FILELENGTH - 1 && fscanf(ifp, "%c", &txtFile[0]) == 1)
{
y++;
}

if(y == FILELENGTH - 1)
{
you ran out of buffer, but at least no harm was done.
}
else
{
txtFile[y] = '\0';
}

--
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)
Nov 5 '06 #2
How do I use fgets?


Richard Heathfield wrote:
to********@gmai l.com said:
How do I get fscanf to copy into an array?

One element at a time.
I also need to use malloc,
but where do I put it in my file?

At the point where you first need the memory. Be sure to #include <stdlib.h>
for the malloc prototype.
FILE *ifp;

char c;
int y = 0;

txtFile = (char *) malloc(FILELENG TH * sizeof(char)) ;

txtFile = malloc(FILELENG TH * sizeof *txtfile);
if(txtFile != NULL)
{

printf ("Enter the name of the file to analyze : ");
gets (filename);

Don't use gets. It's a buffer overflow waiting to happen. Instead, use
fgets, find the newline using strchr, and overwrite it with '\0' if it's
found. (If it's not found, you probably don't want to accept the filename
anyway.)
printf ("\n");
ifp = fopen(filename, "r");

if (ifp == NULL)
{
fprintf (stderr, "Error opening file\n");
exit (-2);
}
while(fscanf (ifp, "%c", &c) != EOF)

I recommend == 1 rather than != EOF. fscanf returns the number of fields
successfully converted, and you're expecting one field, so that's what you
should test for.
{
txtFile[y] = c;
y++;
}

This is fine provided y never equals or exceeds the array bound. But, to
answer your question(!), you can instead do this:

y = 0;
while(y < FILELENGTH && fscanf(ifp, "%c", &txtFile[0]) == 1)
{
y++;
}

if(y == FILELENGTH)
{
you ran out of buffer, but at least no harm was done.
}

If you plan to use txtFile as a string, don't forget to null-terminate it,
which entails leaving space for a null terminator:

y = 0;
while(y < FILELENGTH - 1 && fscanf(ifp, "%c", &txtFile[0]) == 1)
{
y++;
}

if(y == FILELENGTH - 1)
{
you ran out of buffer, but at least no harm was done.
}
else
{
txtFile[y] = '\0';
}

--
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)
Nov 5 '06 #3
to********@gmai l.com writes:
How do I use fgets?
Please don't top-post. Read the following:

http://www.caliburn.nl/topposting.html
http://www.cpax.org.uk/prg/writings/topposting.php

Please don't quote the entire article to which you're replying; quote
only the portions that are relevant to your followup.

How do you use fgets()? You start by reading its description in
whatever textbook or tutorial you're using to learn C, or by reading
the system documentation ("man fgets" on some systems) to find out how
it's used.

We can answer questions here, but we can't teach you the entire
language. The most valuable think you can learn is how to find out
these things for yourself.

--
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.
Nov 5 '06 #4

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
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 ?
5
424
by: learner | last post by:
I have datafiles like this: 0 1941 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.02 0.00 0.00 1 0 1941 0.00 0.03 0.00 0.03 0.04 0.02 0.00 0.00 0.00 0.00 2 0 1941 0.00 0.00 0.00 0.00 0.52 0.00 0.00 0.17 1.07 0.09 3 0 1941 0.04 0.00 0.00 0.00 0.00 0.62 0.00 0.01 0.00 0.00 4 0 1941 0.00 0.02 0.00 0.00 0.00 0.22 0.00 0.00 0.00 0.16 5 0 1941 0.00 0.00 0.00 0.00 0.09 0.04 0.00 0.00 0.00 0.00 6 0 1941 0.00...
9
3228
by: quyvle | last post by:
I can't seem to get this function to work correctly. I'm wondering if anyone could help me out with this. So I'm using the fscanf function to read the input stream and store each string in the appropriate variables. Here's what I'm reading from another file: "# Number of power catergories: 9"
6
3731
by: InuY4sha | last post by:
Hi, I hope to be not off topic.. I have a string on a file "00:32:43:54:A2:2D" (let's say a MAC address) I use fscanf like this fscanf( file, "%02X:%02X:%02X:%02X:%02X:%02X", ptr, ptr+1, ptr+2, ptr3, ptr+4, ptr+5); It works, but I get warnings as the expected size is int while I'm storing onto a uint8_t array.. is there a format to store onto a
10
4470
by: Roman Zeilinger | last post by:
Hi I have a beginner question concerning fscanf. First I had a text file which just contained some hex numbers: 0C100012 0C100012 ....
59
5593
by: David Mathog | last post by:
Apologies if this is in the FAQ. I looked, but didn't find it. In a particular program the input read from a file is supposed to be: + 100 200 name1 - 101 201 name2 It is parsed by reading the + character, and then sending the remainder into fscanf() like
2
11406
by: wilco | last post by:
Hi, im filling a 2D array using fscanf and reading from a csv file. the problem is the file im reading from has some blank spaces which causes any information following to be output as an error. Is there any way of ignoring the blank spaces in the csv file (excel) and continuing to the next number? # include<stdio.h> # include <stdlib.h> # include<math.h>
0
9636
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
9474
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
10139
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8961
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...
1
7485
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6727
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
5373
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
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.