473,911 Members | 5,861 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

First C program

Hi Guys,

This is my first C program. I started programming in Python. Please look
over this source and let me know if I'm doing anything wrong. I want to
start out right with C, so if you see anything wrong tell me now while I
am learning!

Thanks !!!
#include <stdio.h>

int octet0; /* Declare first octet of our IP range */
int octet1; /* Declare second octet of our IP range */
int octet2; /* Declare third octet of our IP range */
int octet3; /* Declare fourth octet (the one we generate) of our IP range */

FILE *outputFile; /* Declare the file in which we will write the IP range to */

int main() /* This is the correct way to declare main... do not use void main() */
{

octet0 = 192; /* Value of first octet */
octet1 = 168; /* Value of second octet */
octet2 = 1; /* Value of third octet */

outputFile = fopen("ips_c.tx t", "wt"); /* Create a text file, open it in write mode */
for (octet3 = 1; octet3 < 255; ++octet3) {
/* printf ("%d.%d.%d.%d\n ", octet0, octet1, octet2, octet3); */
fprintf (outputFile, "%d.%d.%d.%d\n" , octet0, octet1, octet2, octet3);
}
fclose(outputFi le);
printf ("\nThe file 'ips_c.txt' was generated successfully... \n\n");
return(0);
}


Nov 13 '05 #1
27 3152
"hokiegal99 " <ho********@hot mail.com> wrote in message
news:3F******** ******@hotmail. com...
Hi Guys,

This is my first C program. I started programming in Python. Please look
over this source and let me know if I'm doing anything wrong. I want to
start out right with C, so if you see anything wrong tell me now while I
am learning!
Thou hast already committed thy first sin, my son. :-)

The first C program one should write is the classic
"Hello world".

But let's take a look.

First, if you share code here, if at all possible post
*compilable* code. Of course the fastest way for anyone
to spot any syntax errors is to paste your code into a
compiler and compile it. This I did, but first I had
to spend time deleting all those > characters. Actually,
their presence makes me suspect you copied that out of
a newsgroup post or email message.

Also, learn to indent your code. What does the example
code in your textbook look like? Is it all left aligned
like that? Which textbook(s) are you reading?


Thanks !!!
#include <stdio.h>

int octet0; /* Declare first octet of our IP range */
int octet1; /* Declare second octet of our IP range */
int octet2; /* Declare third octet of our IP range */
int octet3; /* Declare fourth octet (the one we generate) of our IP range */

1. Those comments are worse than useless. They only clutter
the code and give no additional information. The identifier
names you're using (which are pretty good ones btw) already
convey the information in the comments (except the 'IP' part)

If I commented this part at all, I'd write something like:

/* IP address octets */
int octet0;
int octet1;
int octet2;
int octet3;

Actually I'd put these values in an array, but you're probably
not that far with the language yet.

2. There's no reason to put these at file scope. They should
go inside your 'main()' function, where they're used.

FILE *outputFile; /* Declare the file in which we will write the IP range to */

Another useless comment. Your (again good) identifier name
'outputFile' tells the story : it's an output file. If you
want to convey that the file will contain 'IP addresses',
perhaps a name like 'IPFileOut' or similar might be closer.

This object should also be defined inside your 'main()'
function, not here.

int main() /* This is the correct way to declare main... do not use void main() */

Correct. Though preferred would be

int main(void)

{

octet0 = 192; /* Value of first octet */
octet1 = 168; /* Value of second octet */
octet2 = 1; /* Value of third octet */
More useless comments.

Also, these values could be specified at definition time
with initializers (these definitions should be inside
this function anyway):

int octet0 = 192;
int octet1 = 168;
int octet2 = 1;
int octet3 = 0;
/* technically initialization of 'octet3' is not necessary,
since you assign it a value below before using it. But
I find that *always* initializing *every* object with
*some* valid value is a good defensive practice. If
you don't give an initial value, and forget to do so
before trying to access it, you get 'undefined behavior.'
Not Good(tm) */

outputFile = fopen("ips_c.tx t", "wt"); /* Create a text file, open it in write mode */

There's no standard 'open mode' of "wt". C streams are
'text mode' by default, unless otherwise specified.
Just use "w".

Also, very important is that you check that the call to
'fopen()' succeeded before trying to touch the file.
If 'fopen()' failed, any attempts at i/o result in,
you guessed it, undefined behavior. :-)

if(outputFile == NULL)
{
puts("Cannot open input");
return EXIT_FAILURE; /* 'EXIT_FAILURE' needs #include <stdlib.h>
}

} for (octet3 = 1; octet3 < 255; ++octet3) {
This will iterate for values of 'octet3' of 1 through
254 inclusive. If you want to include 255, change the
< to <= or compare against 256 with <. I also see you
start with 1 and not zero. This range of values may be
what you want, I don't know. Just drawing attention to
it just in case.
/* printf ("%d.%d.%d.%d\n ", octet0, octet1, octet2, octet3); */
fprintf (outputFile, "%d.%d.%d.%d\n" , octet0, octet1, octet2, octet3);

You need to check that 'fprintf()' succeeded here.
See your compiler manual or textbook to find out how.
}
fclose(outputFi le);
printf ("\nThe file 'ips_c.txt' was generated successfully... \n\n");
return(0);
Nitpick: This is valid, but the parentheses are not
needed. 'return' is not a function, it's a keyword.
}


All in all, not bad. But again, you first should have
written the "Hello world" program. Now go forth and
sin no more. :-)

-Mike
Nov 13 '05 #2
Mac
On Tue, 30 Sep 2003 16:25:14 +0000, hokiegal99 wrote:
Hi Guys,

This is my first C program. I started programming in Python. Please look
over this source and let me know if I'm doing anything wrong. I want to
start out right with C, so if you see anything wrong tell me now while I
am learning!

Thanks !!!
#include <stdio.h>

int octet0; /* Declare first octet of our IP range */
int octet1; /* Declare second octet of our IP range */
int octet2; /* Declare third octet of our IP range */
int octet3; /* Declare fourth octet (the one we generate) of our IP range */

FILE *outputFile; /* Declare the file in which we will write the IP range to */

int main() /* This is the correct way to declare main... do not use void main() */
{

octet0 = 192; /* Value of first octet */
octet1 = 168; /* Value of second octet */
octet2 = 1; /* Value of third octet */

outputFile = fopen("ips_c.tx t", "wt"); /* Create a text file, open it in write mode */
for (octet3 = 1; octet3 < 255; ++octet3) {
/* printf ("%d.%d.%d.%d\n ", octet0, octet1, octet2, octet3); */
fprintf (outputFile, "%d.%d.%d.%d\n" , octet0, octet1, octet2, octet3);
}
fclose(outputFi le);
printf ("\nThe file 'ips_c.txt' was generated successfully... \n\n");
return(0);
}
>


Mike Wahler already critiqued the code. I'll just add that fclose()
returns a value, so if you are going to claim that you successfully wrote
the file, you should probably check the return value of fclose().

Mac
--
Nov 13 '05 #3
hokiegal99 wrote:
Hi Guys,

This is my first C program. I started programming in Python. Please look
over this source and let me know if I'm doing anything wrong. I want to
start out right with C, so if you see anything wrong tell me now while I
am learning!

Thanks !!!
#include <stdio.h>

int octet0; /* Declare first octet of our IP range */
int octet1; /* Declare second octet of our IP range */
int octet2; /* Declare third octet of our IP range */
int octet3; /* Declare fourth octet (the one we generate) of
our IP range */

FILE *outputFile; /* Declare the file in which we will write the IP
range to */

int main() /* This is the correct way to declare main... do not
use void main() */
{

octet0 = 192; /* Value of first octet */
octet1 = 168; /* Value of second octet */
octet2 = 1; /* Value of third octet */

outputFile = fopen("ips_c.tx t", "wt"); /* Create a text file,
open it in write mode */
for (octet3 = 1; octet3 < 255; ++octet3) {
/* printf ("%d.%d.%d.%d\n ", octet0, octet1, octet2, octet3); */
fprintf (outputFile, "%d.%d.%d.%d\n" , octet0, octet1, octet2,
octet3);
}
fclose(outputFi le);
printf ("\nThe file 'ips_c.txt' was generated successfully... \n\n");
return(0);
}


Nice work for a C newbie. The only "error" I can see is not checking
that fopen has worked before writing to your file -- oh, and giving
a mode of "wt" rather than "w" to fopen(). And maybe getting the range
of your "for" loop off-by-one.

As you might expect, though, this is not very idiomatic C. Here's
a "translatio n" of your code that sticks close to the orginal in
spirit, but that is more idiomatic:

#include <stdio.h>
#include <stdlib.h> /* for exit statuses */

int main (void)
{
const char *outfile = "ips_c.txt" ;
FILE *fp; /* it's not usually necessary to give very descriptive
names to streams -- it's generally pretty clear from
context what they're for.
*/
int ip_octet[4];
int i;

ip_octet[0] = 192;
ip_octet[1] = 168;
ip_octet[2] = 1;

fp = fopen(outfile, "w");
if (fp == NULL) {
fprintf(stderr, "Failed to open '%s' for writing\n", outfile);
exit(EXIT_FAILU RE);
}

for (i=0; i<255; i++) {
ip_octet[3] = i + 1;
fprintf(fp, "%d.%d.%d.%d\n" , ip_octet[0], ip_octet[1],
ip_octet[2], ip_octet[3]);
}

fclose(fp);

printf("The file '%s' was was generated successfully\n" ,
outfile);

return 0;
}
--
Allin Cottrell
Department of Economics
Wake Forest University, NC

Nov 13 '05 #4
hokiegal99 wrote:
Hi Guys,

This is my first C program. I started programming in Python. Please look
over this source and let me know if I'm doing anything wrong. I want to
start out right with C, so if you see anything wrong tell me now while I
am learning!

Thanks !!!
#include <stdio.h>

int octet0; /* Declare first octet of our IP range */
int octet1; /* Declare second octet of our IP range */
int octet2; /* Declare third octet of our IP range */
int octet3; /* Declare fourth octet (the one we generate) of
our IP range */

FILE *outputFile; /* Declare the file in which we will write the IP
range to */

int main() /* This is the correct way to declare main... do not
use void main() */
{

octet0 = 192; /* Value of first octet */
octet1 = 168; /* Value of second octet */
octet2 = 1; /* Value of third octet */

outputFile = fopen("ips_c.tx t", "wt"); /* Create a text file,
open it in write mode */
for (octet3 = 1; octet3 < 255; ++octet3) {
/* printf ("%d.%d.%d.%d\n ", octet0, octet1, octet2, octet3); */
fprintf (outputFile, "%d.%d.%d.%d\n" , octet0, octet1, octet2,
octet3);
}
fclose(outputFi le);
printf ("\nThe file 'ips_c.txt' was generated successfully... \n\n");
return(0);
}


The objective of your program is to print the string representation of dotted
decimal IP addresses in a particular network. You have the right idea, but you
are being a bit overzealous. How about this...

#include <stdio.h>

int
main(void)
{
int host;

for(host=1; host < 256; ++host)
printf("192.168 .1.%d\n", host);
return 0;
}

Invoke as

./a.out > ips_c.txt

or embed the file I/O in the program as before.

/david

--
FORTRAN was the language of choice
for the same reason that three-legged races are popular.
-- Ken Thompson, "Reflection s on Trusting Trust"

Nov 13 '05 #5
"Mac" <fo*@bar.net> wrote in message
news:pa******** *************** *****@bar.net.. .
Mike Wahler already critiqued the code. I'll just add that fclose()
returns a value, so if you are going to claim that you successfully wrote
the file, you should probably check the return value of fclose().


I always forget something. :-) Thanks.

-Mike
Nov 13 '05 #6
Mike Wahler wrote:
"hokiegal99 " <ho********@hot mail.com> wrote in message
news:3F******** ******@hotmail. com...

#include <stdio.h>

int octet0; /* Declare first octet of our IP range */
int octet1; /* Declare second octet of our IP range */
int octet2; /* Declare third octet of our IP range */
int octet3; /* Declare fourth octet (the one we generate) of our IP


range */


Something I would add on this level is that using an unsigned char
instead of int might be prudent in many cases like the above. You have
already declaired that they are "octets" which by definition are single
bytes (on any modern day computer) so you could just use bytes. Don't
use simply "char" because it is compiler specific whether or not "char"
is signed, so make sure by calling it unsigned explicitly.

You could also get fancy and pad a known 4 byte integer; in reality this
is what an IP address is. At the level of this program though that is
undue complexity and overhead.

NR

Nov 13 '05 #7
hokiegal99 <ho********@hot mail.com> wrote:
This is my first C program. I started programming in Python. Please look


<snip>
int octet0; /* Declare first octet of our IP range */
int octet1; /* Declare second octet of our IP range */
int octet2; /* Declare third octet of our IP range */
int octet3; /* Declare fourth octet (the one we generate) of our IP range */


toss the globals. They make for confusing code in the end. Learn to use
structs. a convenient way to do it is:

typedef struct _foo_t {
int bar;
char *baz;
struct _foo *recursive;
} foo_t;

The _t at the end quickly identifies it as a datatype, and emacs will
highlight it as a datatype for you; I'm an emacs user so that makes things
nice for me. If you *must* have globals for things like handling signals
then you can always access them like so:

int access_foo(int new, int do_set){
static int foo = 0;
if(do_set){
foo = new;
return 0;
} /* end of if */
else {
return foo;
} /* end of else */
} /* end int access_foo(...) *?

Effectively you are using globals, but the wrapper allows you to later on
do whatever you want, perhaps look it up in a database or something.
As someone who's had to debug 22,000 lines of spaghetti code w/ globals-
galore, written by 4 different physicists over 15 years, I know the dangers
of using globals. Don't make the same mistake.

Also, my personal style is to create a foo.h for every foo.c

I put everything that the rest of the world would ever want to know about
foo.c in foo.h, which does *not* include many #defines, or *any*
static function declarations; o yeah, any function that does not need to
be used by another .c file should be declared static so as not to clutter
the namespace. If you look around in large c programs you see enormous
function names because ansi c does not support namespaces.

Most c coders also use names separated by _'s instead of mixing the
capitalization, at about 6 in the morning when you're brain is incapable
of inserting the space you'll begin to appreciate that tactic.

kudos to you for playing w/ c by the way.

--
Harrison Caudill | .^ www.hypersphere.org
Computer Science & Physics Double Major | | Me*Me=1
Georgia Institute of Technology | '/ I'm just a normal guy
Nov 13 '05 #8
On Mon, 29 Sep 2003 20:07:41 -0700, "Mac" <fo*@bar.net> wrote:
On Tue, 30 Sep 2003 16:25:14 +0000, hokiegal99 wrote:
Hi Guys,

This is my first C program. I started programming in Python. Please look
over this source and let me know if I'm doing anything wrong. I want to
start out right with C, so if you see anything wrong tell me now while I
am learning!

Thanks !!!
#include <stdio.h>

int octet0; /* Declare first octet of our IP range */
int octet1; /* Declare second octet of our IP range */
int octet2; /* Declare third octet of our IP range */
int octet3; /* Declare fourth octet (the one we generate) of our IP range */

FILE *outputFile; /* Declare the file in which we will write the IP range to */

int main() /* This is the correct way to declare main... do not use void main() */
{

octet0 = 192; /* Value of first octet */
octet1 = 168; /* Value of second octet */
octet2 = 1; /* Value of third octet */

outputFile = fopen("ips_c.tx t", "wt"); /* Create a text file, open it in write mode */
for (octet3 = 1; octet3 < 255; ++octet3) {
/* printf ("%d.%d.%d.%d\n ", octet0, octet1, octet2, octet3); */
fprintf (outputFile, "%d.%d.%d.%d\n" , octet0, octet1, octet2, octet3);
}
fclose(outputFi le);
printf ("\nThe file 'ips_c.txt' was generated successfully... \n\n");
return(0);
}
>


Mike Wahler already critiqued the code. I'll just add that fclose()
returns a value, so if you are going to claim that you successfully wrote
the file, you should probably check the return value of fclose().


For that matter, there could also be an error during fprintf().

Nick.
Nov 13 '05 #9
Nick Austin <ni**********@n ildram.co.uk> wrote:
On Mon, 29 Sep 2003 20:07:41 -0700, "Mac" <fo*@bar.net> wrote:
On Tue, 30 Sep 2003 16:25:14 +0000, hokiegal99 wrote: <SNIP>
outputFile = fopen("ips_c.tx t", "wt"); /* Create a text file, open it in write mode */
for (octet3 = 1; octet3 < 255; ++octet3) {
/* printf ("%d.%d.%d.%d\n ", octet0, octet1, octet2, octet3); */
fprintf (outputFile, "%d.%d.%d.%d\n" , octet0, octet1, octet2, octet3);
}
fclose(outputFi le);
printf ("\nThe file 'ips_c.txt' was generated successfully... \n\n");
return(0);
}
>


Mike Wahler already critiqued the code. I'll just add that fclose()
returns a value, so if you are going to claim that you successfully wrote
the file, you should probably check the return value of fclose().


For that matter, there could also be an error during fprintf().

.... as Mike already pointed out in his first reply.

Irrwahn
--
Great minds run in great circles.
Nov 13 '05 #10

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

Similar topics

5
8813
by: Ron Adam | last post by:
Hi, I'm having fun learning Python and want to say thanks to everyone here for a great programming language. Below is my first Python program (not my first program) and I'd apreciate any feedback on how I might do things differently to make it either more consice, readable, or faster. ie... are there better ways to do it in Python? It won't break any records for calculating pi, that wasn't my goal, learning Python was. But it might...
30
2181
by: Pieter Provoost | last post by:
Hi, I just made my first c++ program, and I would like to know if there are things I can do better. Also, the exe is about 500 kb, can I make it smaller? Thanks! Pieter
13
2154
by: Todd | last post by:
I am curious of the origins of the "Hello World" program. Who was the first to make this popular? That is, where did it start? I did some Google search and did not find an answer. Was it Kerringan and Richie? I no longer have that book and I don't remember if it was in that ubiquitous C book. It was so long ago.
5
5446
by: cj | last post by:
Thanks to everyone that has helped me. Now I'm trying to write my first program. I have an example of one that I need to write about. Any help getting me started is appreciated. I'm having trouble getting my compiler to work, access to my a drive is denied, anyone know why this is? Ok here is the info for my program: The two laws of electricity are used in this program. Law #1 The first is Ohm's Law which relates voltage, curret, and...
26
2280
by: mwt | last post by:
Hello. Today I wrote my first program in C. It adds up the elements in an array. I am just beginning to learn this language. Any tips or pointers about better ways to write/structure/format/etc. this code would be much appreciated. Thanks. mwt. #include <stdio.h> int add_array(int arr, int arr_size) {
16
4837
by: Martin Joergensen | last post by:
Hi, I wanted to try something which I think is a very good exercise... I read in data from the keyboard and store them in a structure. There's a pointer called "data_pointer" which I use to keep track on the structures... But it's a bit confusing - my program won't compile and I don't know what to do about the warnings/error messages. c:\documents and settings\dell\Desktop\test\main.c(5) : warning
7
1768
by: Chris Lasher | last post by:
Hi all, I have a simple script: --- #!/usr/bin/env python a = 1 b = 2
3
419
by: cs | last post by:
Hi, I'm new to C and would appreciate any feedback on the following program, asplit, which splits a file into 2 new files, putting a certain number of lines in the first file, and all the rest in the second file. Any comments as to non-portability, stylistic infelicities, outright bugs or anything else would be very much appreciated.
4
5716
by: Fritjolf | last post by:
Hi. I've got a strange problem... I've made a simple program to test encryption/decryption. I use Rijndael encryption and here are the most important properties. RijndaelManaged cipher = new RijndaelManaged(); cipher.KeySize = 256; cipher.BlockSize = 256;
0
10038
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
11349
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
10921
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...
1
11057
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
9728
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
8099
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
5940
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
4341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3360
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.