Hi there,
How can I change my code (below) so that I use an "input argument" to
specify the file name of the input file? For example, if I compile the code
and that the application then gets the name "splitdata" , then I want to be
able to call my application with something like this (datafile.txt will then
be the name of the input file):
splitdata datafile.txt
In the code as I have it now, the name of the input file is specified in
line 13:
char tname[] = "Example.tx t";
So, I want to skip this "hard coded" name specification. (The length of the
input file name is not known.)
Thanks in advance,
MM
=============== =============== =============== ========
=== Code, including line numbers (without line numbers is below this one)
===
=============== =============== =============== ========
1: #include <stdio.h>
2: #include <stdlib.h>
3: #include <string.h>
4:
5: #define DATASTART "\\Data:"
6: #define BLOCKSTART "Time"
7:
8: int main()
9: {
10: FILE *fh, *fp, *fq;
11: char hname[] = "header.dat "; // name of header output file
12: char fname[6+2+4+1]; // name of data block output files,
dblockNN.dat
13: char tname[] = "Example.tx t"; // name of input file to split
14: char buf[1001]; // max line length is 1000 characters
15: char numdb[] = "NumDataBlocks= ";
16: int i = 0;
17:
18: // open input file for reading
19: if((fq=fopen(tn ame, "r")) == 0) {
20: perror(tname);
21: exit(EXIT_FAILU RE);
22: }
23:
24: // open header output file
25: if((fh=fopen(hn ame, "w")) == 0) {
26: perror(fname);
27: exit(EXIT_FAILU RE);
28: }
29:
30: // print data to header file
31: // if start of data segment is found then close header file
32: while(fgets(buf , sizeof buf, fq) != 0) {
33: if(strncmp(DATA START, buf, 6) == 0) {
34: fclose(fh);
35: break;
36: }
37: fputs(buf, fh);
38: }
39:
40: // write data block output files
41: while(fgets(buf , sizeof buf, fq) != 0) {
42: // lines starting with '#' and blank lines are skipped
43: if(buf[0] == '#' || buf[0] == '\n')
44: continue;
45:
46: // write each block to a separate file
47: if(strncmp(BLOC KSTART, buf, 4) == 0) {
48: if(i > 0)
49: fclose(fp);
50: sprintf(fname, "dblock%02d.dat ", ++i);
51: if((fp=fopen(fn ame, "w")) == 0) {
52: perror(fname);
53: exit(EXIT_FAILU RE);
54: }
55: }
56: fputs(buf, fp);
57: }
58:
59: // close files
60: fclose(fp);
61: fclose(fq);
62:
63: // open header output file again and print the number of data blocks
found last in the file
64: if((fh=fopen(hn ame, "a")) == 0) {
65: perror(fname);
66: exit(EXIT_FAILU RE);
67: }
68: sprintf(numdb, "%s%d%s", numdb, i, "\n");
69: fputs(numdb, fh);
70: fclose(fh);
71:
72: return 0;
73: }
=============== ==========
=== Code without line numbers ===
=============== ==========
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DATASTART "\\Data:"
#define BLOCKSTART "Time"
int main()
{
FILE *fh, *fp, *fq;
char hname[] = "header.dat "; // name of header output file
char fname[6+2+4+1]; // name of data block output files,
dblockNN.dat
char tname[] = "Example.tx t"; // name of input file to split
char buf[1001]; // max line length is 1000 characters
char numdb[] = "NumDataBlocks= ";
int i = 0;
// open input file for reading
if((fq=fopen(tn ame, "r")) == 0) {
perror(tname);
exit(EXIT_FAILU RE);
}
// open header output file
if((fh=fopen(hn ame, "w")) == 0) {
perror(fname);
exit(EXIT_FAILU RE);
}
// print data to header file
// if start of data segment is found then close header file
while(fgets(buf , sizeof buf, fq) != 0) {
if(strncmp(DATA START, buf, 6) == 0) {
fclose(fh);
break;
}
fputs(buf, fh);
}
// write data block output files
while(fgets(buf , sizeof buf, fq) != 0) {
// lines starting with '#' and blank lines are skipped
if(buf[0] == '#' || buf[0] == '\n')
continue;
// write each block to a separate file
if(strncmp(BLOC KSTART, buf, 4) == 0) {
if(i > 0)
fclose(fp);
sprintf(fname, "dblock%02d.dat ", ++i);
if((fp=fopen(fn ame, "w")) == 0) {
perror(fname);
exit(EXIT_FAILU RE);
}
}
fputs(buf, fp);
}
// close files
fclose(fp);
fclose(fq);
// open header output file again and print the number of data blocks
found last in the file
if((fh=fopen(hn ame, "a")) == 0) {
perror(fname);
exit(EXIT_FAILU RE);
}
sprintf(numdb, "%s%d%s", numdb, i, "\n");
fputs(numdb, fh);
fclose(fh);
return 0;
} 7 7536
# splitdata datafile.txt
#
# In the code as I have it now, the name of the input file is specified in
# line 13:
#
# char tname[] = "Example.tx t";
#
# So, I want to skip this "hard coded" name specification. (The length of the
# input file name is not known.)
# 8: int main()
int main(int argc,char **argv) {...}
On systems that provide a command line interface, if you call the program with
'splitdata datafile.txt', usually it will set
argc = 2
argv[0] = "splitdata"
argv[1] = "datafile.t xt"
argv[2] = 0
So you can do something like
char *tname = argc>=2 ? argv[1] : "Example.tx t";
--
Derk Gwen http://derkgwen.250free.com/html/index.html
GERBILS
GERBILS
GERBILS
"Derk Gwen" <de******@HotPO P.com> wrote in message
news:vg******** ****@corp.super news.com... int main(int argc,char **argv) {...}
On systems that provide a command line interface, if you call the program
with 'splitdata datafile.txt', usually it will set argc = 2 argv[0] = "splitdata" argv[1] = "datafile.t xt" argv[2] = 0
So you can do something like char *tname = argc>=2 ? argv[1] : "Example.tx t";
Yes, that works just fine! Many thanks for the help.
MM
"MM" <do*******@yaho o.se> wrote: How can I change my code (below) so that I use an "input argument" to specify the file name of the input file? For example, if I compile the code and that the application then gets the name "splitdata" , then I want to be able to call my application with something like this (datafile.txt will then be the name of the input file):
splitdata datafile.txt
That's called "command line arguments" in C, not "input arguments". To
use them, you define main() as
int main(int argc, char argv**)
and read your C book for a complete explanation of these arguments. In a
nutshell, though:
- argc contains the number of arguments plus one.
- If argc>0, then argv[0] contains the name of the program (though not
necessarily in a format that's useful to you, especially if you need
directory information).
- If argc>1, then argv[1] through argv[argc-1] are the command line
parameters.
- argv[argc] is a null pointer.
Richard
"David Rubin" <no****@nowhere .net> wrote in message
news:md******** **********@twis ter.nyc.rr.com. .. MM wrote:
[snip] int main() { [snip] char numdb[] = "NumDataBlocks= "; [snip] sprintf(numdb, "%s%d%s", numdb, i, "\n");
This yields undefined behavior since you're trying to write more bytes
than you've allocated for numdb.
/david
Ok, then is this a better way to do it?
[snip]
char numdb[4+2+1+1];
[snip]
sprintf(numdb, "%s%02d%s", "NDB=", i, "\n");
Also, maybe you have a nice way to (platform independently!) remove/delete a
file in C?
Using for example
system("del filename.txt");
doesn't work, of course, since "del" is not OK in UNIX...
Thanks again, David!
MM
"MM" <do*******@yaho o.se> wrote in
news:e5******** ********@nntpse rver.swip.net: Ok, then is this a better way to do it?
[snip] char numdb[4+2+1+1]; [snip] sprintf(numdb, "%s%02d%s", "NDB=", i, "\n");
Probably.
Also, maybe you have a nice way to (platform independently!) remove/delete a file in C? Using for example system("del filename.txt"); doesn't work, of course, since "del" is not OK in UNIX...
remove()
On Thu, 10 Jul 2003 15:44:43 +0200, in comp.lang.c , "MM"
<do*******@yaho o.se> wrote: "David Rubin" <no****@nowhere .net> wrote in message news:md******* ***********@twi ster.nyc.rr.com ... MM wrote:
[snip] > int main() > { [snip] > char numdb[] = "NumDataBlocks= "; [snip] > sprintf(numdb, "%s%d%s", numdb, i, "\n");
This yields undefined behavior since you're trying to write more bytes than you've allocated for numdb.
Ok, then is this a better way to do it?
make numdb big enough (malloc sounds like a useful method), and don't
copy it into itself which ISTR is also undefined behaviour.
bigenough = strlen("NumData Blocks=") + aslongas_i_coul d_be +2);
char* numdb = malloc(bigenoug h);
sprintf(numdb, "NumDataBlocks= %d\n", i);
Also, maybe you have a nice way to (platform independently!) remove/delete a file in C?
remove();
RTFM !!
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
On Thu, 10 Jul 2003 15:44:43 +0200, "MM" <do*******@yaho o.se> wrote: "David Rubin" <no****@nowhere .net> wrote in message news:md******** **********@twis ter.nyc.rr.com. .. MM wrote: [snip] char numdb[] = "NumDataBlocks= "; [snip] sprintf(numdb, "%s%d%s", numdb, i, "\n");
This yields undefined behavior since you're trying to write more bytes than you've allocated for numdb.
Plus the (total) overlap, as noted elsethread.
Ok, then is this a better way to do it?
[snip] char numdb[4+2+1+1]; [snip] sprintf(numdb, "%s%02d%s", "NDB=", i, "\n");
As long as the value of i fits in two digits this is valid; if it is
larger, *printf will expand the field, and for sprintf overflow.
Using snprintf as of C99, or in many C89s as an extension possibly
under a variant name like _snprintf, you can prevent overflow and UB,
but (instead) get incomplete output you must check for and deal with.
If the string NDB is constant, it is simpler and IMO preferable to
include it in the format string:
snprintf (numdb, sizeof numdb, "NDB=%02d\n ", i);
and if the string varies I would consider something like:
char numdb[sizeof("NDB=") -1 +2+1+1] = "NDB=";
...
snprintf (numdb+4, 2+1+1, "%02d\n", i);
In either case, the %02d forces a _minimum_ two digits; if you don't
need this, and your format would be unambiguous and legible without,
%d is sufficient and simpler.
But, in your original code, the only thing you do with this output is
write it to a file. You could accomplish that with fprintf and not
need to worry about ensuring or checking that your line buffer is (at
least) the right size; output files are as large as necessary, at
least up to platform limits you probably cannot exceed anyway.
- David.Thompson1 at worldnet.att.ne t This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: zhi |
last post by:
Really confused, when I use keyword style argument as following:
>>> input(prompt="hello")
Traceback (most recent call last):
File "<pyshell#52>", line 1, in -toplevel-
input(prompt="hello")
TypeError: input() takes no keyword arguments
While the library reference says the function is: input( )
|
by: Hoegje |
last post by:
I am writing a C++ program, which should create a sub- process to
start a telnet session to another server. Then it should login to that
server (on the telnet login) and execute one or more command(s) on the
remote server. The C++ program provides all the input for this process
(username, password, servername, commands, ...) and should capture all
the output returned by the telnet session process inside some
variable. How can this be...
|
by: Raffi |
last post by:
Hi folks,
I'm new to JavaScript and need some help.
I have a form with a select field. Depending on what is selected in
this field, I want to display or not display another select field. For
example first field asks the user if they drive, if the user selects
"NO" the form doesn't change. If they select "YES", another field
appears with different makes to chose from. If they change back to "NO"
the second field dissapears again.
|
by: Generic Usenet Account |
last post by:
I am trying to set up a delimiter character string for the input stream
such that the delimiter string is "skipped over" in the input stream.
Can someone suggest how to do this with some sample code? I am
attaching a "C" code snippet that does the same thing. The problem is
that I don't know how to realize this using "cin"
Thanks,
Lee
|
by: moostafa |
last post by:
Hi,
I'm writing a program that performs arithmetic operations on integers.
I want to be able to type in a bunch of integers seperated by any
amount of white space then terminate input with a non-integer
character. I plan to put my input into an array, and while I have a max
size I don't have a min and don't know exactly how many arguments to
expect.
I would really appreciate any ideas.
Cheers.
| |
by: ohaqqi |
last post by:
Hi everybody. I haven't programmed anything in about 8 years, I've read up a little bit on C and need to write a shell in C. I want to use strtok() to take an input from a user and parse it into the command and its arguments.
for example: copy <file1> <file2> will copy file 2 to file 1, del <file1> will delete a file, etc. The exit command is all I've implemented right now, but even that produces an error when executed...I'm sure I've got a...
|
by: Thomas Pajor |
last post by:
Hey everybody,
I got into serious trouble with template programming. I have a class
which uses three template arguments, say
template<typename Atype, typename Btype, typename Ctype>
class some_class {
};
|
by: leannsmarie |
last post by:
Hi Everyone,
I have a problem with a program I have been assigned thats driving me crazy and I hope someone with a fresh eye could point me in the right direction. Im using Visual Basic Express 2008 on WinXP and the program is a Windows Form application.
The application has to calculate a total order for wire spools and display the shipping status. The form has a text box to accept the total number of spools being ordered (Integer), labels to...
|
by: James Mills |
last post by:
On Fri, Oct 31, 2008 at 8:49 AM, mark floyd <emfloyd2@gmail.comwrote:
Mark, this is correct behavior. You have
3 positional arguments in the function
definition. You _must_ aupply _all_ 3
of them. If you wish for b to be optional,
then you must give it a default value.
def foo(a, b=None, c=None):
print a
|
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,...
|
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...
| |
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...
|
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...
|
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...
|
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();...
|
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...
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |