473,902 Members | 3,721 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to count rows and columns of integers/doubles in a file?

Hi,

I have some files which has the following content:

0 0 0 0 0 0
0 1 1 1 1 0
0 1 1 1 1 0
0 1 1 1 1 0
0 1 1 1 1 0
0 0 0 0 0 0

I'm making a function for a bigger program, that

1) counts number of columns in each row
2) verifies that there are the same number of columns in each row
(if not: error + quit)
3) increments row count after one row is finished
4) stops execution if it encounters anything that is not an
integer (later: should also work for doubles)

My only problem is that I don't know how to switch line (carriage
return) or how to detect it using scanf. Besides that, the
program is almost finished. See below:
- - - - - - - - - - - - - - - -
#include <stdio.h>
void int_getdata(cha r *filename, unsigned int *x, unsigned int
*y);
int main()
{
unsigned int n_x[3], n_y[3];

int_getdata("un knowns.dat", &n_x[0], &n_y[0] );
int_getdata("BC _types.dat", &n_x[1], &n_y[1] );
// double_getdata( "BC_values.dat" , &n_x[2], &n_y[2] );

return 0;
}

void int_getdata(cha r *filename, unsigned int *x, unsigned int
*y)
{
FILE *fp;

unsigned int old_nx;
int int_readvalue, returnvalue;
//double double_readvalu e;

old_nx = 0; /* reset */
*x = 0;
*y = 0;

if ( (fp = fopen(filename, "r") ) == NULL)
{
printf("Cannot open file %s.\n", filename);
system("PAUSE") ; /* give the user at chance to see this
error before the windows shuts down */
exit(1);
}

/* get nx and ny */
do{
returnvalue = fscanf(fp, "%i", &int_readvalue) ; /* all
input must be valid */

if(returnvalue == 1) (*x)++; /* nx is getting larger */
else{
printf("Error: non-valid input found in %s.\n",
filename);
exit(1);
}

if(int_readvalu e == '\n')
{
if(old_nx != 0 && old_nx != *x)
{
printf("ERROR: nx is not a constant in file
%s!\n", filename);
exit(1);
}
else /* we should now be sure that nx is constant and
move on to the next input line */
{
old_nx = *x;
y++; /* ny is getting larger */
*x = 0;
}
}
} while(returnval ue != EOF);

printf("\nFinis hed reading from file %s: (x,y) = (%i,%i).\n",
filename, *x, *y);
fclose(fp); /* close input file, finished reading values in
*/
}

- - - - - - - - - - - - - - - -

I hope somebody can help me solve this small problem, so I can
finish the program....

I also get these small warnings, but they are not critical:

warning C4013: 'system' undefined; assuming extern returning int

warning C4013: 'exit' undefined; assuming extern returning int
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk

Mar 15 '06
68 6859
Mark F. Haigh wrote:
Martin Jørgensen wrote: -snip-

It may "work", but it's certainly a childish effort, at best. Let me
guess, you're a first year student? Your code sucks. Unclear,
unmaintainable, unportable. Amateur.
No, I'm not a first a first year student.
<snip>
It is not a homework assignment.


<snip>
It is not a homework assignment.

Very cute. I'm impressed. I think all of us are.


I see you have a very big problem with me telling you that this wasn't a
homework assignment. You don't have to be impressed by that. That is
nothing.
Notice that nowhere have you:

1. Described concisely the format of the file you wish to be able to
parse. Do you control the file format? Or is it generated by another
program not under your control?


I did that already in the beginning of the thread:

Hi,

I have some files which has the following content:

0 0 0 0 0 0
0 1 1 1 1 0
0 1 1 1 1 0
0 1 1 1 1 0
0 1 1 1 1 0
0 0 0 0 0 0


You can replace some of them with decimal numbers if you don't trust me.

2. Described what you wish to do with the file. What's the point of
this exercise? What's the big picture? I take it you want to read it
into a multidimensiona l array so you can manipulate it somehow. What
for?

You have to help us so we can help you. We're not mind readers!


I already told that a couple of times: Now I want to get number of rows
and number of cols for malloc'ing a 2D-array. You don't have to be a
mind reader to understand that. I wrote that a couple of times since
<k3********** **@news.tdc.dk> and I even posted a program that just don't
compile in <fs***********@ news.tdc.dk> and I don't know why.

We all know why it doesn't compile. It's because you don't know what
you're talking about. Your code sucks. Most regulars here can write
the complete program you've been struggling with for 3 days in about 10
minutes.


Wauw... Am I supposed to be impressed now?

I have other things to do, than to program.
So if
there's any problem in answering this question, the reason is not that
you aren't a mind reader.

Fuck off. You are quite possibly the most worthless programmer (and
human being) I've ever seen. You'll get no further responses.

I have better things to do than waste my time dealing with morons like
you.
Mark F. Haigh
mf*****@sbcglob al.net


.... "with morons like you"... Look who's talking now...

What exactly is your problem?

"the most worthless programmer (and human being) I've ever seen".

"Fuck off".
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Mar 19 '06 #41
CBFalconer wrote:
Martin Jørgensen wrote:
Mark F. Haigh wrote:


... snip ...
You have to help us so we can help you. We're not mind readers!


I already told that a couple of times: Now I want to get number of
rows and number of cols for malloc'ing a 2D-array. You don't have
to be a mind reader to understand that. I wrote that a couple of
times since <k3************ @news.tdc.dk> and I even posted a
program that just don't compile in <fs***********@ news.tdc.dk> and
I don't know why. So if there's any problem in answering this
question, the reason is not that you aren't a mind reader.

Now don't get all snippy with your panties in a knot, or you will
find your help rapidly disappears. We all have better things to do
than laboriously research a thread. Articles should stand by
themselves, and if something is unclear just explain it. Articles
should also be short.


I already explained it several times, pretty clear IMO, but if people
don't want to read what is very clear then it not my fault. Do I really
have to remind you, that Pedro already solved this problem without
whining like a pig like Mark who has a problem which I never understood
and probably never will understand.

I just answered his questions and assured him that this wasn't a
homework exercise - what else should I do? I really don't see his
problem and those stupid accusations is just too much.
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Mar 19 '06 #42
Richard G. Riley wrote:
On 2006-03-17, Martin Jørgensen <un*********@sp am.jay.net> wrote:
Michael Mair wrote:
-snip-

Cheers
Michael


Do you like my new program?

I find it *REALLY* useful :-)

Hi Martin,

I think you need to take a step back and consider making it about
1/3rd of the size and 100 times more readable. I really believe you
have overcomplicated this : as a result of you learning C as you go I suspect.

Some hints:

1) create a struct for representing rows & column count - then have an
array of these. all this n_x and n_y is not nice on the eye. And be
concistent in your naming conventions. "y" is not a proper
alternative for "number of columns".
2) Consider reading in the data a line at the time using fscanf/fgets or
something. Reading in by character is often inefficient.
3) What is "count" and why are you passing a reference to it when the
function always increments it? Sloppy. Return a success/fail code.
4) never call a function "getdata" and especially never make such a
function a void IMO : return a success code or a count or a pointer
to a result of interest.
5) stop exiting from the lower level funtions. If you *must* have a
function called "testwronginput " return a success code and
certainly do not pass in pointers to column & row data : it doesnt
need to know about them - it should only be interested in the
character it is checking. You have complicated this function and
made it heavy on the eye. Keep it simple.
6) I'm always suspicous of anything which counts anything in a "next"
line. It should be counting things in "current" line. Whenever I
see two calls to something like "countColsInNex tLine" next to each
other I have to wonder if there is a better, clearer way to handle
it. Often turning the loop upside down works.
7) comment your functions : good clear C is self explanatory
manytimes, unfortunately functions like "testwronginput " are far
from clear - it seems an almost arbitrary attack on various forms
of white space etc. Hence a spec would be appreciated.

Finally : use google. I googled "reading lines in from file in c" ...

http://www.mrx.net/c/program.html

fgets might be helpful. fcanf even more so for a strict input
format. How "strict" is your input detail? Maybe its ok to assume the
format is rigid?

It is still far from clear what format the data file is in. Explain
this clearly in words - not as a c comment.

good luck!

-snip-

Hi Richard. Thanks for the professional and constructive contribution.
Those suggestions look pretty good to me. This thread has been
"polluted" a bit too much for me, I think.

The good thing is that I think I have the programming part under
control, more or less...
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Mar 19 '06 #43
CBFalconer wrote:
Martin Jørgensen wrote:
Barry Schwarz wrote:

-snip-

Sorry, your formatting makes it impossible to compile your code
and I didn't spot these in my review.


Okay, forget about this wrapping thing. Guess you're right. I
just can't restrict Visual studio from making lines longer than
65 characters or so. I went through all the options and help. The
following should be better in that I don't think it inserts
ekstra linebreaks in places never intended to have linebreaks. So
what's important is what's inside main() and I hope that
copy/pasting should work - I manually fixed some comments etc.


... snip ...
void getdata(char *filename, unsigned *pCols, unsigned *pRows, int *count)
{
FILE *pFile;

unsigned rows, cols, oldcols;

printf("Opening file: %s.\n", filename);
if ( (pFile = fopen(filename, "r") ) == NULL)
{
printf("Cannot open file %s.\n", filename);
/* give the user at chance to see this error before the windows
shuts down */
system("PAUSE") ;
exit(1);
}

As an example, lets just deal with the above extract, and see a
reasonable way to format it that will work everywhere.

void getdata(char *filename, /* room to describe */
unsigned *pCols, /* the various parameters */
unsigned *pRows, /* if desired */
int *count)
{
FILE *pFile;

unsigned rows, cols, oldcols;

printf("Opening file: %s.\n", filename);
if ( (pFile = fopen(filename, "r") ) == NULL) {
printf("Cannot open file %s.\n", filename);

/* give the user at chance to see this error */
/* before the windows shuts down */
system("PAUSE") ;
exit(1);
}

And, instead of the very questionable use of system("PAUSE") etc.,
I would use:

printf("Cannot open file %s.\n"
"Hit <enter> to continue",
filename);
fflush(stdout);

/* give the user at chance to see this error */
/* before the windows shuts down */
getchar();
exit(EXIT_FAILU RE);
}

Note the use of string concatenation to avoid long lines, and
simultaneously provide an image of the output screen in the source
code. Now that portion is also portable. You can also easily
change to using fprintf(stderr, "..., which is a preferable place
for error messages.


I get the idea, but don't be surprised about that I'm going to tell you
that I couldn't possible know that you felt that way about reading some
code I copy/pasted since I haven't subscribed to this group for long and
only have about 1,5 months of C programming experience.

I guess I have subscribed to this group for about 1,5 months and being
called "a moron", being told to "fuck off" and being told that "You are
quite possibly the most worthless programmer (and human being) I've ever
seen" is just too childish.
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Mar 19 '06 #44
On Sun, 19 Mar 2006 07:18:56 -0500, in comp.lang.c , CBFalconer
<cb********@yah oo.com> wrote:
Martin Jørgensen wrote:
void getdata(char *filename, unsigned *pCols, unsigned *pRows, int *count)
{


void getdata(char *filename, /* room to describe */
unsigned *pCols, /* the various parameters */
unsigned *pRows, /* if desired */
int *count)


personally I consider this an abomination. The first form is way more
readable.

Please don't put comments to the right of your variable declarations,
if you have some comment to make, do it above the code where it can be
sensibly read and isn't going to end up bizarrely indented when
variable names get altered. .
Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Mar 19 '06 #45
Mark McIntyre <ma**********@s pamcop.net> writes:
On Sun, 19 Mar 2006 07:18:56 -0500, in comp.lang.c , CBFalconer
<cb********@yah oo.com> wrote:
Martin Jxrgensen wrote:
void getdata(char *filename, unsigned *pCols, unsigned *pRows, int *count)
{


void getdata(char *filename, /* room to describe */
unsigned *pCols, /* the various parameters */
unsigned *pRows, /* if desired */
int *count)


personally I consider this an abomination. The first form is way more
readable.


I work for a company that has the latter as required style.
(If you violate it you get scorched in code reviews.)
--
"Given that computing power increases exponentially with time,
algorithms with exponential or better O-notations
are actually linear with a large constant."
--Mike Lee
Mar 19 '06 #46
Richard G. Riley schrieb:
6) I'm always suspicous of anything which counts anything in a "next"
line. It should be counting things in "current" line. Whenever I
see two calls to something like "countColsInNex tLine" next to each
other I have to wonder if there is a better, clearer way to handle
it. Often turning the loop upside down works.


The (potential) misnomer is my fault -- as long as it is not
clear that there is a line, I like to think of the potential
input line as "next line if any".
If we had some sort of readLine(&line, ....) and a check whether
a line has been read, then a subsequent call to a line counting
function could of course call countColsInCurr entLine(line, ....)
or countColsInLine ().

The original code is from me (<47*********** *@individual.ne t>):
,---
rows = 0;
if (countColsInNex tLine(pFile, &oldcols) != EOF) {
rows++;
while (countColsInNex tLine(pFile, &cols) != EOF) {
rows++;
if (cols != oldcols) {
isConsistent = 0;
/* Your error message here */
}
}
}
`---
The two calls "next to each other" maybe could be done
in a nicer way -- the alternative to differentiate between
"oldcols unset because we have not yet read in the first
line" and "oldcols set" within the loop IMO is a poor one.
I went with the obvious course: "If there is no line, ...;
if there is at least one line, set oldcols; if there are
further lines, compare oldcols with the new line's number
of columns".
How would you express that differently in C without putting
tests that do not structurally belong there inside the
loop?

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Mar 19 '06 #47
Martin Jørgensen wrote:
.... snip ...
I guess I have subscribed to this group for about 1,5 months and
being called "a moron", being told to "fuck off" and being told
that "You are quite possibly the most worthless programmer (and
human being) I've ever seen" is just too childish.


You didn't get that from me, and usenet is full of ignorant boors.
Ignore them, or at least their boorish behaviour.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
Mar 19 '06 #48
CBFalconer opined:
Martin Jørgensen wrote:
... snip ...

I guess I have subscribed to this group for about 1,5 months and
being called "a moron", being told to "fuck off" and being told
that "You are quite possibly the most worthless programmer (and
human being) I've ever seen" is just too childish.


You only got that from one person (I can vouch for two out of three),
on one occasion, and they have already been criticised for it (by
me ;-) ).
You didn't get that from me, and usenet is full of ignorant boors.
Ignore them, or at least their boorish behaviour.


Good advice. Heed it.

--
BR, Vladimir

Tact is the ability to tell a man he has an open mind when he has a
hole in his head.

Mar 19 '06 #49
On 2006-03-19, Ben Pfaff <bl*@cs.stanfor d.edu> wrote:
Mark McIntyre <ma**********@s pamcop.net> writes:
On Sun, 19 Mar 2006 07:18:56 -0500, in comp.lang.c , CBFalconer
<cb********@yah oo.com> wrote:
Martin Jxrgensen wrote:
void getdata(char *filename, unsigned *pCols, unsigned *pRows, int *count)
{

void getdata(char *filename, /* room to describe */
unsigned *pCols, /* the various parameters */
unsigned *pRows, /* if desired */
int *count)


personally I consider this an abomination. The first form is way more
readable.


I work for a company that has the latter as required style.
(If you violate it you get scorched in code reviews.)


Required always, or required for non-self-explanatory argument lists
and/or argument lists over a certain length?

In other words, are we talking about

void f(void /* room to describe void */
)

or is there some wiggle room here?
Mar 19 '06 #50

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

Similar topics

1
1597
by: Dejavous | last post by:
Hi there, I'm a SQL Server 2000 noob and looking for some help. I need to make a simple script that counts the number of rows in a table. Also, i need to make another version ofthe same script, but ONLY look and count rows with certain data in them...e.g. search and count for rows with the word JOE in them. Any help would be really appreciated, and if somebody would be so kind to break down and explain each part of the script i would be...
1
1471
by: dukefrancis | last post by:
Can anyone tell me how to find the count of columns from a table????
3
1554
by: sheesh | last post by:
hi how am i able to input rows of integers from another file for eg num.txt inside the text file it is as shown 1 3 5 2 4 6 7 9 11 i tried doing so but still couldn't get it string s;
1
1340
by: neehakale | last post by:
If anybody of you knows how to count the no of rows in the excel file then pls tel me....
0
3006
by: JFKJr | last post by:
I have an excel file, which has columns C and D grouped together, I am trying to delete blank columns and rows from the excel file, ungroup the columns and import the file to MS Access using Access VBA code. The following is the Access VBA code I used to delete blank columns and rows in the excel file. But, unfortunately, the resultant excel file still has two columns (C and D) grouped together, so when I am importing the file to MS Access,...
1
1921
by: mojo123 | last post by:
Hi All, I am looking for a way to count rows in datagrid. The code I have goes something like this: Data1.DatabaseName = Mydata.mdb Data1.Recordsoource = Select * Table1 Where Class = 3 And Group=2 Data1.Refresh How can I count the number of current rows/record in a datagrid. Any Help will be greatl appreciated.
6
2929
by: viki1967 | last post by:
Hi all. I need your help. I realize this script and I do not know where to begin: 1) A simple grid rows / columns. 2) The first column contain an input type = "checkbox" 3) When select the input type, the line should change color than the other rows, and you should open a popup window.
3
7053
by: ronakinuk | last post by:
how can i unhide rows/columns in excel 2007
0
9997
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
9845
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
11279
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...
1
10981
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
9673
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
8047
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
7205
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
5893
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...
2
4306
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.