anyone can help me on a code to open a file..for example..a.txt..using VC++ and display it in another file, lets say b.txt
Printable View
anyone can help me on a code to open a file..for example..a.txt..using VC++ and display it in another file, lets say b.txt
What have you done so far? From what you described that sounds like reading from a file and writing to a file. If you're using MFC, the first thing to try might be finding the right class - (think of a class name and prepend a capital C) - CFile.
Jay
Besides that I wouldn't see that much sense in open a file, reading in the content and write it to another file (you would simply copy the file which is less code ;) )...there are several options...for example using STL...
Other than that...you can also use the MFC counterparts such as 'CFile', 'CStdioFile' etc.Code:#include <string>
#include <fstream>
#include <iostream>
int main()
{
// Open files
std::ifstream in("c:\\test.txt");
if(!in)
return -1; // Could not open file
std::ofstream out("c:\\test_out.txt");
if(!out)
return -1; // Could not open file
// Read line-by-line
std::string t;
while(std::getline(in, t))
out << t;
// Close files
in.close();
out.close();
return 0;
}
thanx for the reply ..but there are few errors that occured..
c:\documents and settings\owner\my documents\time3.cpp(13) : error C2143: syntax error : missing ';' before 'if'
c:\documents and settings\owner\my documents\time3.cpp(19) : error C2065: 'file' : undeclared identifier
c:\documents and settings\owner\my documents\time3.cpp(19) : fatal error C1903: unable to recover from previous error(s); stopping compilation
Error executing cl.exe.
can anyone help me??
There was a missing semicolon...and a wrong variable name...it is fixed now...sorry about that...
If you want to copy a file why don't you simply use CopyFile()?
Or you can do this:
Code:// Open files
std::ifstream in("d:\\test.txt");
if(!in)
return -1; // Could not open file
std::ofstream out("d:\\test_out.txt");
if(!out)
return -1; // Could not open file
std::istreambuf_iterator<char> iit(in), iitEnd;
std::ostreambuf_iterator<char> oit(out);
std::copy( iit, iitEnd, oit);
// Close files
in.close();
out.close();
You can also use the following codes to read it:
CString strPathX = AfxGetApp()->m_pszHelpFilePath;
strPathX = strPathX.Left(strPathX.ReverseFind('\\'));
CString strOtherFile;
strOtherFile = strPathX+_T("\\example.txt");
CStdioFile m_File;
if(m_File.Open(strOtherFile,CFile::modeRead | CFile::typeText))
{
CString strTemp;
int nNumber = 100;
while (m_File.ReadString(strTemp))
{
strTemp.TrimLeft();
strTemp.TrimRight();
if(!strTemp.IsEmpty())
{
}
}
m_File.Close();
}
Jack
---------------------------------------------------------------------------------
XD++ MFC/C++ Flow/Diagram Library -- http://www.********.net
Sometimes, I wonder why people no longer use good ol' C.
I mean what is it in CFile that you cant do with FILE.
here's what i would do
#include <cstdio>
int main()
{
FILE *fin;
FILE *fout;
char buffer[512];
int read;
fin = fopen( "example.txt", "rb" );
if( !fin ) return -1;
fout= fopen( "newfile.txt", "wb" );
if( !fout ) { fclose(fin); return -1; }
while(!feof(fin))
{
read=fread( buffer, 1, 512, fin );
fwrite( buffer, 1, read, fout );
}
fclose(fin);
fclose(fout);
return 0;
}
thanx for the reply..
i think CFILE can be used..
the codes can run well..
i have another query..
How bout if I wanna change the time in a.txt with a current time..(replacing the syntax with time format in a.txt)
example in a.txt
time 12:30 ..in the codes whenever the codes sees - -:- - format..it change it to 1:00 and b.txt will display the time as 1:00
You can use CFile for read and write also. Check for the write functions available with CFile Class.
You can use system command, and pass the file name path to it
off topic: please use code tags (see the Code button on the toolbar).
When in Roam, do as Romans do ;) When using MFC, do as MFC does, when using C++, do as C++ does and when using C, do as C does. :thumb:Quote:
Originally Posted by yash_sws
thanx for the reply anreas,
the codes can run well, however the output format of the file is different from the input file..can anyone help me fix the code abit so that
the output format is the same as the input format (such as paragraph in output is the same as paragraph in input)
this is the codes :
#include <string>
#include <fstream>
#include <iostream>
int main()
{
// Open files
std::ifstream in("c:\\test.txt");
if(!in)
return -1; // Could not open file
std::ofstream out("c:\\test_out.txt");
if(!out)
return -1; // Could not open file
// Read line-by-line
std::string t;
while(std::getline(in, t))
out << t;
// Close files
in.close();
out.close();
return 0;
}
Sometimes using low level functions are simpler, try this code below:
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char* argv[])
{
int iRead, iWrote;
int iInFd, iOutFd;
char Buf[1024];
if ( (iInFd = open ("c:\\test.txt", O_RDONLY)) < 0)
return -1;
if ( (iOutFd = open ("c:\\test_out.txt", O_RDWR|O_BINARY|O_CREAT|O_TRUNC, S_IWRITE)) < 0)
return -1;
while ( (iRead = read(iInFd, Buf, 1024)) > 0)
if ( (iWrote = write (iOutFd, Buf, iRead)) != iRead)
return -1;
return 0;
}
Well...what is different? Missing line-breaks? In this case...Quote:
Originally Posted by scootz3345
should help...Code:while(std::getline(in, t))
out << t << std::endl;
Besides that...if you simply want to copy a file there are easier methods... ;
thanx man...actually this is just a part of a program...:)
i am finding how to change the content of the opened file n come out with the output in a new file...
thanx for the help
whats the different between struct, pointer and array???
lets if i have words, name:my name is eric stored in a file a.txt
how can it be detected so that " my name is eric " can be stored in a variable "name" ??
can anyone help me???
The variable name has to be there during compiling, thus cannot be applied dynamically at run-time...other than that you simply parse your file...
Code:#include <string>
#include <fstream>
#include <iostream>
int main()
{
// Open file
std::ifstream in("c:\\test.txt");
if(!in)
return -1; // Could not open file
// Read line-by-line
std::string t;
std::string name;
while(std::getline(in, t))
{
std::string::size_type pos = t.find("name:");
if(pos != std::string::npos)
name = t.substr(pos + 1);
}
// Close file
in.close();
std::cout << name << std::endl;
return 0;
}
thanx again for the code!
the code is compiled and run successfully, however it didn't produce any output...can u help me find whats wrong with it ??
really appreciate it!
Well...I would simply assume that there is no "name:" string in the file...can you upload the file here?
ok..thanx..i'll upload the file..
actually im just using the variable "name" as an example.
This is a sample of a syslog file.
Actually what im trying to do is, if u see in the example.txt, there is a word
"date=2005-04-26". I want the code to detect "date=" and return the
value of "2005-04-26" into a variable so that it can be sent to the
database field. And then also return other values such as "device_id"
and "log_id".
Thanx so much !!
Well...I don't see "date=" or anything else you mentioend in the file...however, you simply need to exchange the 'name:" in the 'find()' function to the appropriate search value you want...e.g. "date=".
Same goes for extracting the data....if they are in the middle of the line you need to calculate both the beginning (by using 'find()') and the end (by using 'find()' again for example)...
sorry..my bad...i have posted a wrong file...
this is the correct file..
can u write me an example using find() from this file??
I have managed to open the file n separate the content, however i have this problem where
display_string(buffer, "date=", 'a');
:
:
:
void display_string( char *buff, char *str, char flag )
{
char *plocation;
int pos=0;
char *tmp = buff;
char d[100];
char ff = flag;
int j=0;
int len = strlen(str);
switch(ff)
{
case 'a':
len=len+10;
break;
case 'b':
len=len+8;
break;
as u can see im reading it by counting the line after each word in case example "date=" ---len+10..10 character after the word "date=" will be consider as date..
however i have problems..what if we set it as 14..the date only contain of 10 so it will also display the balance of other 4 character..
it will display them as well..example "12-10-2005 sed" 14 character
how can i make it so that it will not take any other character after the space???
plocation = strstr( tmp, str);
pos = plocation - tmp;
if (plocation)
{ cout<<"\n\t";
//cout<<"\nThe time of this entry is:"<<endl;
for(int i=pos;i<pos+len;i++)
{
//do{
d[j]=buff[i];
//cout<<buff[i];
//}while (d[j]!=[ ]);
cout<<d[j];
j++;
}
//cout <<pos<<endl;
}
Change the following part of my previous code
Not tested though....Code:// Read line-by-line
std::string t;
std::string pattern("date=");
std::string date;
// Get one line
while(std::getline(in, t))
{
// Find the beginning position in the string of the following pattern
std::string::size_type pos = t.find(pattern);
// Check whether we reached the end of the string (-> pattern not found)
if(pos != std::string::npos)
{
// Extract the value of the pattern. The value starts at the returned
// position plus the length of the pattern and ends at the next space.
// Thus, we need to find the next space beginning at pattern position.
// The returned position then needs to be recalculated so that we get
// the number of characters we want to extract. Thus, we subtract
// the beginning position plus the length of the pattern from the
// position of the space...
data = t.substr(pos + pattern.length() , t.find(" ", pos) - pos + pattern.length());
}
}
there's 1 error:
this is the whole codes:
#include <string>
#include <fstream>
#include <iostream>
int main()
{
char data;
char name;
// Open file
std::ifstream in("samplesyslog.txt");
if(!in)
return -1; // Could not open file
// Read line-by-line
std::string t;
std::string pattern("date=");
std::string date;
while(std::getline(in, t))
{
std::string::size_type pos = t.find(pattern);
if(pos != std::string::npos)
{
data = t.substr(pos + pattern.length() , t.find(" ", pos) - pos + pattern.length());
}
}
// Close file
in.close();
std::cout << date << std::endl;
return 0;
}
This is the error:
C:\Documents and Settings\Administrator\My Documents\3 June 2005\adreas maseur\sample5.cpp(23) : error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class
std::allocator<char> >' (or there is no acceptable conversion)
Error executing cl.exe.
sample5.obj - 1 error(s), 0 warning(s)
Please test it for me...thanx
It should be
Code:date = t.substr(pos + pattern.length() , t.find(" ", pos) - pos + pattern.length());
I think this should be nominated for the Question Of The Month awardQuote:
Originally Posted by scootz3345
thanx andreas, u help me alot.
however, the output takes the value of date and also the next string..
example, output: 2005-04-26 time:18:3
and please if can u explain a bit how the code works so that i can expand it for other variables.
thanx!
Well...that should be my fault I guess....it should have beenQuote:
Originally Posted by scootz3345
Code:date = t.substr(pos + pattern.length() , t.find(" ", pos) - (pos + pattern.length()));
I have added comments to my previous reply....Quote:
Originally Posted by scootz3345
Dear scootz3345,
For this kind of work the Perl language is a much better choice, especially if you have to cope with more difficult text parsing tasks. Since you seem rather unexperienced in the C++ language maybe this is the time to switch. Your example would be expressed in Perl as follows:
Just store the code in the file syslogdate.pl, no need to compile and link.Code:# Open file
open(IN, "samplesyslog.txt") or die "Can't open your file\n";
# Read line by line and find the last occurrence of "date="
while (<IN>) {
# Store text next to it up to the next whitespace in $date
$date = $1 if /date=(\S*)/ ;
}
# Close file
close(IN);
# Print result
print "$date\n";
Sample data in file samplesyslog.txt
Then type syslogdate.pl at the command prompt:Code:blah blah
system date=01/02/2005
Now let's try a date followed by other stuff:
and another date=02/03/2005 time=18:34
note that the word date without an = immediately following it won't match.
Perl should have been installed first, it is available for free download. Start at http://www.perl.orgCode:D:\Proj\Perl>syslogdate.pl
02/03/2005
OK, now about parsing YOUR sample syslog. Try this:
The program output will be:Code:open(IN, "samplesyslog.txt") or die "Can't open your file\n";
# read line by line and find the last occurrence of a number of named fields
while (<IN>) {
# Extract several fields and store them in variables
$date = $1 if /\bdate=(\S*)/ ;
$time = $1 if /\btime=(\S*)/;
$log_id = $1 if /\blog_id=(\S*)/;
$service = $1 if /\bservice=(\S*)/;
}
close(IN);
print "Log timestamp is $date, $time (Reference ID=$log_id)\n";
print "File Transfer Protocol\n" if $service eq "ftp";
print "Domain Name Service\n" if $service eq "dns";
Note the \b prefix in "\btime" was used to match only "time" starting at a word boundary.Code:D:\Proj\Perl>syslogdate.pl
Log timestamp is 2005-04-26, 18:36:56 (Reference ID=0022010001)
File Transfer Protocol
Exercise for the reader: Try to get the same result in C++. And ask yourself which program is more elegant, self-explanatory.
Note: I am an experienced C++ programmer, but for text parsing jobs I can't beat Perl.
thanx guys..ya..its deffinately easier to do it in Perl with the foreach() function. but its already set for me to do it in C++, kinda difficult.
I will try to expand the codes. Thanx again!!
Adreas, thanx man...wanna ask u something, is it the "std::string pattern("date=");" can only be used once??
which part of the codes should i modify if i wanted to display other variables??
and one more thing, the codes only takes the last time value..if u go though the file there is actually a lot of time value..
can u help modify the codes so that the output will be something like this??
i'll send u a sample codes that produce the output..
But when you are using MFC, you must be using C++. I can't see any reason to use MFC CFile over C++ streams. Remember MFC is very old now and was invented before Microsoft was especially interested in adding the STL to their compiler.Quote:
Originally Posted by Ejaz
Markus
Quote:
Originally Posted by yash_sws
I wonder why this compiles. According to footnote 160 in the section 17.4 of the C++ standard, if you include the newer headers (cstdio instead of stdio.h etc) then the names from those headers go into namespace std and not into the global namespace.
Markus
What do you mean with only once?Quote:
Originally Posted by scootz3345
You need to understand how the concept works...you read the file line-by-line...thus, you read in one line and parse it. While having this line, you can search for whatever you want. So...in other words....the code within the while loop in my example exactly deals with one line...Quote:
Originally Posted by scootz3345
What time value? My code was looking for the date in every line... :confused:Quote:
Originally Posted by scootz3345
oh ya!! your example was using date, it works fine because date only have
one value..
however when i change "date=" to "time=" it only takes the last value of
time that is in the last paragraph of the file...it doesnt work,
in that file, actually there's a lot of time value...which is different for every
log file.
example =
Apr 26 18:33:39 192.168.2.1 date=2005-04-26 time=18:36:38 device_id=APS3012404200864 log_id=0022010001 type=traffic subtype=allowed pri=notice vd=root SN=16863 duration=130 policyid=4 proto=6 service=ssh status=accept src=210.101.234.131 srcname=210.101.234.131 dst=202.189.48.98 dstname=202.189.48.98 src_int=external dst_int=dmz/ha sent=48 rcvd=76 sent_pkt=1 rcvd_pkt=1 src_port=9218 dst_port=22 vpn=n/a tran_ip=203.223.134.2 tran_port=22 dir_disp=org tran_disp=noop
"18:36:38"
Apr 26 18:33:42 192.168.2.1 date=2005-04-26 time=18:36:40 device_id=APS3012404200864 log_id=0022010001 type=traffic subtype=allowed pri=notice vd=root SN=16991 duration=36 policyid=1 proto=6 service=ftp status=accept src=192.168.2.106 srcname=192.168.2.106 dst=209.133.111.196 dstname=209.133.111.196 src_int=internal dst_int=external sent=1003 rcvd=1889 sent_pkt=14 rcvd_pkt=18 src_port=2333 dst_port=21 vpn=n/a tran_ip=202.189.48.98 tran_port=54490 dir_disp=org tran_disp=noop
"18:36:40"
Run the previous codes that i attached above, u'll know what i'am tryin to explain ...sorry for the misconclusion
Well...I don't know why you only have one date....every entry in the given file has one date and one time value.
Thus...the code given should work for both date and time...simply exchange 'date=' with 'time=' and it will give you the time instead...
yeahh..i did change the date with time, but the problem is the file have
different time value in different paragraph (every syslog has the same date,
but different time value) i try to change the date in your codes with time,
what it print only the last value of time. (time value from the last paragraph
in the file)
Try o run this attachment file: Can u help me modify your codes into something like this??
thanx !
Well...is there any reason why you are using old-style character strings instead of the STL 'string' for searching? This is most likely the reason why it behaves different from what I have been posted... ;)
I would need to look deeper into it...however, currently I am a little bit busy for that...you would need until tonight...
No problem..just take your time..yeah..i prefer your way too..
thats y probably you can help me..thanx man!!
That's because the output statement in Andreas' sample in fact belongs inside the while loop in order to print the date (or time, for that matter) for every log entry.Quote:
Originally Posted by scootz3345
Re your attachment openfile1.cpp: Questionable coding.... For several reasons:Quote:
Originally Posted by scootz3345
1) You assume a fixed length of every value in the log file. For date/time values this may be ok, but not for most of the other values. You'd better gather characters until the first blank (assuming no blanks can appear inside an attribute value).
2) Why the flag argument and the huge switch statement instead of directly supplying the value length as an argument?
3) You can't make a temporary copy by justYou only copy the pointer in that case, but both pointers will refer to the original string.Code:char *tmp = buff;
4) Trying to get the values of the "sent" and the "sent_pkt" fields, for example, in this manner won't work (unless they happen to occur in a particular order)
You seem to be missing the basics of the C++ language. I would recommend you to start with a C++ tutorial or use a more beginner-friendly language.
well..actually i didn't know about the STL 'string'..thats why i really need your help on this..thanxQuote:
Originally Posted by Adreas Maseur
std::string pattern("date="); --- how can i modify this for multiple output??Quote:
Originally Posted by scootz3345
std::string pattern("date=","time=","id=") ??
Quote:
Originally Posted by scootz3345