473,320 Members | 1,857 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

trying to read a file

Hi everyone,

I'm trying to read the first line of a file this way:
....
....
....
....
new_line=0;
while((read=read(fd, &info, sizeof(info))) > 0 && !new_line){
if (strcmp(&info, "\n") != 0){
strcat(line,info);
}
else{
new_line=1;
}
}

But i can't find the end of the line and this code goes until the end of the
file instead the end of the line.
The other problem is that i get a segmentation fault in strcat(line, info),
i've declared the variables like this:

char *line="";
char info;

That's all, i hope someone can help me 'cause i can't find the errors.

Thanx.


Nov 14 '05 #1
4 2435
# while((read=read(fd, &info, sizeof(info))) > 0 && !new_line){
# if (strcmp(&info, "\n") != 0){
# strcat(line,info);
# }
# else{
# new_line=1;
# }
# }
#
# But i can't find the end of the line and this code goes until the end of the
# file instead the end of the line.

Check the documentation for the function. Does it say it will add a zero
byte terminator? Not all functions do that.
strcpy(p,q)
adds a zero byte after copying strlen(q) bytes, but
memcpy(p,q,strlen(q))
does not add a zero byte.

# The other problem is that i get a segmentation fault in strcat(line, info),
# i've declared the variables like this:
#
# char *line="";
# char info;

You have to allocate sufficient room for the concatenation before calling
strcat; also on most system you cannot modify a literal string.

--
Derk Gwen http://derkgwen.250free.com/html/index.html
You hate people.
But I love gatherings. Isn't it ironic.
Nov 14 '05 #2
yo_mismo <qw*@rty.com> wrote:
I'm trying to read the first line of a file this way: char *line="";
char info;
...
...
...
new_line=0;
while((read=read(fd, &info, sizeof(info))) > 0 && !new_line){
if (strcmp(&info, "\n") != 0){
strcat(line,info);
}
else{
new_line=1;
}
} But i can't find the end of the line and this code goes until the end of the
file instead the end of the line.
Your first problem is that this is at least partly off-topic in clc,
there's no standard C function called read(). Please ask in a group
that's concerned with your operating system. You probably would have
less problems if you would use a (standard C) function like fget()
instead. Just make sure that 'info' is an int or you won't be able
to detect the EOF (and, of course, use a stream pointer (FILE*)
instead of a file descriptor).
The other problem is that i get a segmentation fault in strcat(line, info),
i've declared the variables like this:


That's no surprise. 'line' is a char pointer, pointing to a string
that contains just the '\0' character. Now, the initialization makes
it point to a "literal string", i.e. a string that can't be changed.
Moreover, even if you would be allowed to change that string, you
still would have only room for a single char (and that's already
taken by the end-of-string delimiter '\0'), so you can't put any-
thing more into it. What you need is either a large enough array of
characters or a dynamically allocated buffer.

Second, you can't use strcmp() and strcat() here. They both work on
strings, i.e. arrays of chars that have a '\0' at the end of the
text they are supposed to contain. But 'info' is just a single char,
not an array of chars. If you haven't silenced your compiler it
should at least complain loudly about your call of strcat() since
the second argument isn't a char pointer but a char (it won't for
strcmp() because you pass it the address of the 'info' char, so it
can't determine that what you pass it won't be a string).

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #3
Je***********@physik.fu-berlin.de wrote:
.... You probably would have less problems if you would use a
(standard C) function like fget() instead.


Sorry, make that fgetc(), there's no function named fget()!

Regards, Jens

--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #4

"yo_mismo" <qw*@rty.com> a écrit dans le message de
news:hD******************@news.ono.com...
Hi everyone,
Hi,

I'm trying to read the first line of a file this way:
...
...
...
...
new_line=0;
while((read=read(fd, &info, sizeof(info))) > 0 && !new_line){
There's no such function (read) in C. According to your requirements, I
would have used characters I/O functions like fgets or getc instead.
if (strcmp(&info, "\n") != 0){
info is a char, not a string. Functions of <string.h> work on strings (i.e
arrays of chars ended with the null terminating character \0) and look for
the null terminating character to process.
It would have worked for example in this case :
/*...*/
char info[2];
info[0] = '\n'; /*or else char..*/
info[1] = '\0';
/* strcmp shall return 0, the expression is evaluated to false*/
if (strcmp(info,"\n") != 0)
{
/*...*/
}
strcat(line,info);
Same remark as above. In addition to that, strcat requires sufficient
allocated space to store the result in line, but you defined line as a
string with only the null terminating character. line may also be read-only.
}
else{
new_line=1;
}
}

But i can't find the end of the line and this code goes until the end of the file instead the end of the line.
The other problem is that i get a segmentation fault in strcat(line, info), i've declared the variables like this:

char *line="";
char info;

That's all, i hope someone can help me 'cause i can't find the errors.
Here is a sample program which reads and displays the first line of a text
file passed in argument, using fgetc or fgets:

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

#define MAX_CHARS_PER_LINE 120

/* #define BASIC */

int main(int argc, char *argv[])
{
FILE * fp;
int c;
char linebuffer[MAX_CHARS_PER_LINE];

strcpy(linebuffer,"nothing");

if (argc < 2)
{
fprintf(stderr, "Not enough arguments\n");
fprintf(stderr, "Usage : readfl <file>\n"
"readfl displays the first line of the text file <file>\n");
exit(EXIT_FAILURE);
}

fp = fopen(argv[1], "r");

if (fp != NULL)
{

#ifdef BASIC

int cnt = 0;
while (((c = fgetc(fp)) != '\n' && c != EOF)
&& cnt < MAX_CHARS_PER_LINE-1)
{
linebuffer[cnt++] = c;
}
linebuffer[cnt] = '\0';

#else

fgets(linebuffer, MAX_CHARS_PER_LINE, fp);

#endif

puts(linebuffer);

fclose(fp);
exit(EXIT_SUCCESS);

}
else
{
fprintf(stderr, "Couldn't open the file to read\n");
exit(EXIT_FAILURE);
}

return 0;
}
HTH
Regis

Thanx.

Nov 14 '05 #5

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

Similar topics

1
by: IronMonk | last post by:
Hi I am trying to edit a text file... the format of which is like #####abc.conf poll somethin proto pop3 via 127.9.02.1 user "me@me.com" pass "dell" is me.nutcase preconnect "abc abc abc...
5
by: jdh2358 | last post by:
I have a python file that is trying to read raw data from a raw partition on a dying dist, eg f = file('/dev/sda') f.seek(SOMEWHERE) s = f.read(SOMEBYTES) On some blocks, the read succeeds,...
3
by: Les Desser | last post by:
In A97 I am trying to determine some attributes of files in a folder - Date, time, file size and file name. To this end I have managed to create a batch file to do a Dir to a work file (and then...
4
by: Jeff Rodriguez | last post by:
Main just loops over this while it's not null. The segfault occurs at this line: *line = (char)ch; Also, please don't just fix the code. I would like to know why exactly this isn't working so I...
4
by: yo_mismo | last post by:
Hi everyone, I'm trying to read the first line of a file this way: .... .... .... .... new_line=0; while((read=read(fd, &info, sizeof(info))) > 0 && !new_line){ if (strcmp(&info, "\n") !=...
3
by: jdjohns74 | last post by:
I've never written a Python program before and I'm trying to read a config file with file path/names (eg. c:\\python24\\*.dll, ... *.exe) to create an ouput file of filename + md5 values. I'm...
1
by: James Johnston | last post by:
I've never written a Python program before and I'm trying to read a config file with file path/names (eg. c:\\python24\\*.dll, ... *.exe) to create an output file of filename + md5 values. I'm...
1
by: jonathan184 | last post by:
trying to rename filenames and extensions then add a header in line1 of each file if the header existed in line 1 to go to the next file. but i am getting error explciti errors Here is my...
7
by: JoeC | last post by:
I am trying to create a windows program that reads binary graphics as a resource. This has nothing to do with win32 but conversion of data with memcpy. graphic::graphic(UINT uiResID, HINSTANCE...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work

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.