473,811 Members | 4,047 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

From file to char* array

Hi,

I've char* array that I defined like char *str[150]. I want to read
from a file, that contains names in each row, and assign them to my str
char * array.

m is a char array, f is a file pointer and counter is my variable that
contains number of names in my file;

When I write;

while(fgets(m,1 00,f)!=NULL) {
printf("%s",m)
}

code. It gets and writes all my names onto screen but;

When I recode it like;

while(fgets(m,1 00,f)!=NULL) {
str[counter]=m;
counter--;
}

and try print str[1] ve str[2] to screen It always print my last
elements for 2 times.

For example:

File: John, Alp, Liz, Sema

First code writes;
John, Alp, Liz, Sema

With second code and printfs:
Sema, Sema

How can I fix it? Thanks so much...

Dec 8 '06 #1
8 3066
OziRus wrote:
Hi,

I've char* array that I defined like char *str[150]. I want to read
from a file, that contains names in each row, and assign them to my str
char * array.
<snip>

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

#define MAX_NAMES 150
#define MAX_NAME_LENGTH 256

int main(int argc, char **argv) {
FILE *f;
char *names[MAX_NAMES];
int cnt;

/* open file */
if(argc < 2) {
fprintf(stderr, "No file specified.\n");
exit(EXIT_FAILU RE);
}
else {
f = fopen(argv[1], "r");
if(f == NULL) {
fprintf(stderr, "Unable to open file: %s\n", argv[1]);
exit(EXIT_FAILU RE);
}
}

/* allocate memory for names */
for(cnt = 0; cnt < MAX_NAMES; cnt++) {
if((names[cnt] = malloc(MAX_NAME _LENGTH * sizeof *names)) == NULL)
{
fprintf(stderr, "No memory.\n");
exit(EXIT_FAILU RE);
}
}

/* read lines into memory */
for(cnt = 0; cnt < MAX_NAMES; cnt++) {
if(fgets(names[cnt], MAX_NAME_LENGTH , f) == NULL && ferror(f)) {
fprintf(stderr, "Error reading file: %s\n", argv[1]);
for(cnt = 0; cnt < MAX_NAMES; cnt++) free(names[cnt]);
exit(EXIT_FAILU RE);
}
}

/* print what we've read in from file */
for(cnt = 0; cnt < MAX_NAMES; cnt++)
fprintf(stdout, "%s", names[cnt]);
fflush(stdout);

for(cnt = 0; cnt < MAX_NAMES; cnt++) free(names[cnt]);
return EXIT_SUCCESS;
}

Dec 8 '06 #2
Thanks. But I still can't understand why

while(fgets(m,1 00,f)!=NULL) {
str[counter]=m;
counter--;
}

doesn't work...

Dec 8 '06 #3
OziRus said:
Thanks. But I still can't understand why

while(fgets(m,1 00,f)!=NULL) {
str[counter]=m;
counter--;
}

doesn't work...
str[counter] = m; does not allocate fresh storage for a copy of your string.
It merely points str[counter] at your existing buffer. So you end up with a
whole bunch of pointers all pointing to the same place. And if you give any
one of those pointers to printf, you'll get the same data printed out.

As santosh has demonstrated, you can fix this by allocating sufficient
storage for each line of data, and by then copying your data into it.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 8 '06 #4

OziRus wrote:
Thanks. But I still can't understand why

while(fgets(m,1 00,f)!=NULL) {
str[counter]=m;
counter--;
}

doesn't work...
The line
fgets(m,100,f)
reads at most 100 bytes of data from FILE f, and places that data into
the character buffer m, overwriting anything that was previously stored
in buffer m

The line
str[counter]=m
takes the address of the first byte of the buffer m (effectively) and
stores that address in str[counter]

It /does not/ copy the contents of the buffer m into str[counter]. For
that, you would have to use something like strcpy()

Once your while loop completes, you have a number of str[] entries all
pointing to the same buffer m

When you print each str[] entry, you print the current contents of
buffer m, which contains the /last/ value retrieved by fgets()

HTH
--
Lew

Dec 8 '06 #5
Thank you so much!

Richard Heathfield yazdi:
OziRus said:
Thanks. But I still can't understand why

while(fgets(m,1 00,f)!=NULL) {
str[counter]=m;
counter--;
}

doesn't work...

str[counter] = m; does not allocate fresh storage for a copy of your string.
It merely points str[counter] at your existing buffer. So you end up with a
whole bunch of pointers all pointing to the same place. And if you give any
one of those pointers to printf, you'll get the same data printed out.

As santosh has demonstrated, you can fix this by allocating sufficient
storage for each line of data, and by then copying your data into it.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 8 '06 #6
OziRus wrote:
Thank you so much!
Please don't top-post. Your replies belong following or interspersed
with properly trimmed quotes. See the majority of other posts in the
newsgroup, or:
<http://www.caliburn.nl/topposting.html >
Dec 8 '06 #7
On 8 Dec 2006 09:24:34 -0800, "santosh" <sa*********@gm ail.comwrote:
>OziRus wrote:
>Hi,

I've char* array that I defined like char *str[150]. I want to read
from a file, that contains names in each row, and assign them to my str
char * array.
<snip>

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

#define MAX_NAMES 150
#define MAX_NAME_LENGTH 256

int main(int argc, char **argv) {
FILE *f;
char *names[MAX_NAMES];
int cnt;

/* open file */
if(argc < 2) {
fprintf(stderr, "No file specified.\n");
exit(EXIT_FAILU RE);
}
else {
f = fopen(argv[1], "r");
if(f == NULL) {
fprintf(stderr, "Unable to open file: %s\n", argv[1]);
exit(EXIT_FAILU RE);
}
}

/* allocate memory for names */
for(cnt = 0; cnt < MAX_NAMES; cnt++) {
if((names[cnt] = malloc(MAX_NAME _LENGTH * sizeof *names)) == NULL)
Why use malloc()? The size of names[cnt] is certainly not unknown or
even "dynamic". Both MAX_NAME_LENGTH and sizeof *names are
compile-time constants.

Why not just declare an appropriate array with either automatic or
static storage duration? If you did that, it:

1. Would free you from having to free().
2. Would result in a smaller memory footprint (less code).
3. Might make the difference between running or not on a non-hosted
environment. Resources can get pretty constrained on, for example,
some embedded systems. Such implementations might not even
*practically* support malloc().
4. Might unnecessarily violate coding standards (thou shall not use
dynamic memory) that are applicable to, for example, safety-critical
systems.

--
jay
>{
fprintf(stderr, "No memory.\n");
exit(EXIT_FAILU RE);
}
}

/* read lines into memory */
for(cnt = 0; cnt < MAX_NAMES; cnt++) {
if(fgets(names[cnt], MAX_NAME_LENGTH , f) == NULL && ferror(f)) {
fprintf(stderr, "Error reading file: %s\n", argv[1]);
for(cnt = 0; cnt < MAX_NAMES; cnt++) free(names[cnt]);
exit(EXIT_FAILU RE);
}
}

/* print what we've read in from file */
for(cnt = 0; cnt < MAX_NAMES; cnt++)
fprintf(stdout, "%s", names[cnt]);
fflush(stdout);

for(cnt = 0; cnt < MAX_NAMES; cnt++) free(names[cnt]);
return EXIT_SUCCESS;
}
Dec 9 '06 #8
On 8 Dec 2006 08:46:41 -0800, "OziRus" <ca************ @gmail.com>
wrote:
<snip>
while(fgets(m,1 00,f)!=NULL) {
str[counter]=m;
counter--;
}
You almost certainly had and wanted counter++ there. Unless you knew
in advance the number of lines you will read, or at least a safe upper
bound, and from the rest of your discussion you don't.

Assuming so, the only problem you have is reusing/sharing the buffer
m, as already answered by others.

If you really have counter-- and are at any time decrementing below
zero, then that is a second problem.

- David.Thompson1 at worldnet.att.ne t
Dec 26 '06 #9

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

Similar topics

4
2790
by: Venkat | last post by:
Hi All, I need to copy strings from a single dimensional array to a double dimensional array. Here is my program. #include <stdio.h> #include <stdlib.h>
39
2661
by: Joe Laughlin | last post by:
If I have a character array with "/some/file/directory/file_name", are there any functions / libraries that I could use to separate the directory ("some/file/directory") from the file name ("file_name"). I looked at sscanf(), but that didn't seem to do what I wanted. Thanks, Joe
1
3331
by: john | last post by:
Relatively new to C coding, so any help would greatly be appreciated. I'm having problems try to return my string array from my parsing function. When I do a printf I am getting the correct value for my first element but my subsequent printf's will return garbage. Can someone let me know what I am doing wrong. Thanks in advance. -jlewis
5
7801
by: Stephen Cawood | last post by:
I'm trying to use a C++ .lib from C# (I tried the Interop group will no results). I have a working wrapper DLL (I can get back simple things like int), but I'm having issues dealing with an array of bytes. For example, the .lib contains this function: int create(int id, int scale, unsigned char *image); In the wrapper DLL I have this function:
0
1492
by: Holly | last post by:
I copied this code that works to connect into Unix. I am looking for a way to get it to work with a secure Unix box. Anyone have any insights on how to do this? I am trying to build an sftp service. Thanks Holly Imports System Imports System.Net Imports System.IO
2
22615
by: Potiuper | last post by:
Question: Is it possible to use a char pointer array ( char *<name> ) to read an array of strings from a file in C? Given: code is written in ANSI C; I know the exact nature of the strings to be read (the file will be written by only this program); file can be either in text or binary (preferably binary as the files may be read repeatedly); the amount and size of strings in the array won't be known until run time (in the example I have it in...
7
3598
by: theballz | last post by:
Hi, I am learning c programming and come across a problem i cant seem to solve. I have a file which i wish to parse and put certain lines (which do not contain a hash character) into an array and then output the contents of this array. The file seems to be parsed properly and the array gets populated but when I output the array the last line of my text file has filled the array. Text file and code as follows, Text File
6
3555
by: Kinbote | last post by:
Hi, I'm trying to make a function that opens a file, reads it in line by line, puts each line into an malloc'd array, and returns the array. I suspect I'm going about it in an atypical fashion, as I'm avoiding the use of fscanf and fgets to read in lines. I don't want to have to specify a temporary char* buffer to read in each line, and then have to concern myself with the (remote) possibility of overflows or with increasing the buffer...
13
10460
by: rohit | last post by:
Hi All, I am new to C language.I want to read integers from a text file and want to do some operation in the main program.To be more specific I need to multiply each of these integers with another set of integers stored in an array.It would be a great help if you could provide some code for it.I tried the function fscanf but by that I am able to read only the first integer of the text file.Please help me.
0
9604
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,...
1
10394
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10127
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
9201
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
7665
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
6882
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
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4336
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
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.