#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
int main(int argc, char* argv[])
{
ifstream ifile;
char fName[30][30];
long int uTime[30][10];
ifile.open("sync.log");
char ch;
string str = "";
if(ifile.fail())
{
cout<<"Invalid File Name!";
system("pause");
exit(1);
}
int i = 0;
while(!ifile.eof())
{
getline(ifile, str);
cout<<str<<endl;
sscanf(str.c_str(),"%ld %[^\n]",&uTime[i],fName[i]);
i++;
str = "";
}
ifile.close();
system("pause");
cout<<"Output:"<<endl;
for(i = 0 ; i < 2 ; i ++)
{
cout<<uTime[i]<<" ";
cout<<fName[i];
cout<<endl;
}
getch();
return 0;
}
File : sync.log
Format:
1399865017 Test1.txt
1399865017 Test1.txt
so here is my full code and i have sync.log file in root directory where the VC++ saved the projects...
It must be stored like this in array after Reading from File
uTime[0] = 1399865017;
fName[0] = "Test1.txt";
fName[1] = "Test1.txt";
with this above code i am getting
uTime[0] = 0012F6B0 and fName[0] = "Test1.txt"
and i want this uTime[0] = 1399865017;
fName[0] = "Test1.txt";
I think you meant to use:
long int uTime[30];
instead of
long int uTime[30][10];
With that, the line that reads data into uTime and the line that write uTime to cout would make sense.
Given that you have:
long int uTime[30][10];
when you do:
cout << uTime[i] << …
you are printing a pointer to an array of 10 long. That pointer is formatted in hex; that is why you are getting hex output.
You need to fix the sscanf() call — you've got a bogus argument of &uTime[i] there — and the output too. Since it is not clear why uTime is a 2D array, it isn't easy to tell you how to fix it, but the simplest solution would be to drop the [10] from the array definition.
Related
I have the following code:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream os;
char fileName[] = "0.txt";
for(int i = '1'; i <= '5'; i++)
{
fileName[0] = i;
os.open(fileName);
os << "Hello" << "\n";
os.close();
}
return 0;
}
The aim is to write my code output into multiple .txt files up to, say 64 different times. When I change this loop to run more than 10, that is
for(int i = '1'; i <= '10'; i++)
I get the following error:
warning: character constant too long for its type
Any ideas how to write to more than 10 files? Moreover, how do I write a number after each "Hello", e.g. "Hello1 ... Hello10"?
Cheers.
I believe the reason you receive that warning is because you're attempting to assign two chars into one slot of the char array:
fileName[0] = i;
because when i = 10;, it's no longer a single character.
#include <fstream>
#include <iostream>
#include <string>//I included string so that we can use std::to_string
using namespace std;
int main() {
ofstream os;
string filename;//instead of using a char array, we'll use a string
for (int i = 1; i <= 10; i++)
{
filename = to_string(i) + ".txt";//now, for each i value, we can represent a unique filename
os.open(filename);
os << "Hello" << std::to_string(i) << "\n";//as for writing a number that differs in each file, we can simply convert i to a string
os.close();
}
return 0;
}
Hopefully this resolved the issues in a manner that you're satisfied with; let me know if you need any further clarification! (:
My HexDump that I have takes a file and outputs the ASCII hex value of that file, and also the binary values of that file. In example, when I run my program on a text file containing "Hello World!", I get
4865 6C6C 6F20 etc. So I know it is converting the direct ascii characters to the correct hex values. But, an example in my program syllabus shows that other bytes should be printed before the text.
This leads me to believe that I am not reading the entire file correctly. I think I may need to use fread() or fopen()? Please help me out. I am a C++ beginner. This is my code that I run on my txt file:
#include <iostream>
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <bitset>
using namespace std;
string stringToHexOrByte(char input, bool toByte)
{
string output;
if (toByte) {
bitset<8> temp(input);
output = temp.to_string();
}
else {
static const char hex_digits[] = "0123456789ABCDEF";
output.reserve(2);
output.push_back(hex_digits[input >> 4]);
output.push_back(hex_digits[input & 15]);
}
return output;
}
int main(int argc, char* argv[]) {
// Create a text string, which is used to output the text file
string initialInput;
// char variable in order to read char by char from file
char myChar;
//bool value to know if we have the byte parameter called
bool byteOption;
// string which will retain the converted char to hex or byte
string convChar;
string fileName;
//Check if we have -b byte Option
if (argc > 2) {
byteOption = true;
fileName = argv[2];
}
else {
byteOption = false;
fileName = argv[1];
}
// Read from the text file
fstream myFile(fileName, fstream::in);
// we will use this group variable to separate the chars printed as in the examples
int group = 1;
while (myFile >> std::noskipws >> myChar) {
// if the bynary option is selected we will print all the chars separetely
if (byteOption) {
group = 0;
}
convChar = stringToHexOrByte(myChar, byteOption);
cout << convChar;
// here we use the group to get the output expected
if (group) {
group = 0;
}
else {
cout << " ";
group = 1;
}
//clear non-printable chars
if ((int)myChar < 32) {
myChar = '.';
}
// Append to input string
initialInput.append(1, myChar);
}
// Close the file
myFile.close();
//print input
cout << " " << initialInput;
return 0;
}
I am learning C++ in one of my classes and I am having difficulties storing the content of a .txt file into a c string.
I have figured out how to validate that the .txt file exists but when I try storing the characters into a c-string it crashes.
This is my most recent attempt:
char * fileContent[MAX_SIZE];
ifstream ifile(argv[1]);
while (int i = 0 < MAX_SIZE)
{
ifile >> fileContent[i];
cout << fileContent[i];
if (ifile.eof())
break;
i++;
}
ifile.close();
Every-time the console gets to the loop it crashes. Are there any suggestions to help make this work?
I need it to be a c-string so that I can run the c-string through other functions. I am still pretty new to C++.
The assignment states: "Reads a text file into memory, one byte at a time"
I hope what I am trying to do is this.
Thank you
You can use the following code to read from a text file and save the string as a C-string. The output file (output.txt) contains the c-string output.
#include <string>
#include <iostream>
#include <fstream>
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
char *out_c_string;
char ch;
int index=0;
while(cin >> ch)
out_c_string[index++] = ch;
for(int i=0; i<index; i++)
cout << out_c_string[i]; // the c string of the file :)
return 0;
}
There were few bugs in your code, try this:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int MAX_SIZE = 128;
int main(int argc, char* argv[])
{
char fileContent[MAX_SIZE]; //bad idea never do that!
// use an std::vector<char> instead!
// and reverse a minimum amount of chars
// using `reserve` if you are after performance
ifstream ifile(argv[1]);
int i = 0;
while (i < MAX_SIZE)
{
ifile >> fileContent[i];
cout << fileContent[i];
if (ifile.eof())
break;
i++;
}
ifile.close();
}
Combining everyones answers, I got this as my function:
void get_file_info(char * argv, char (&fileContent) [MAX_SIZE], int & filesize ){
freopen(argv, "r", stdin);
char ch;
int index = 0;
while (cin >> noskipws >> ch)
fileContent[index++] = ch;
cout << endl << index << endl;
#if SHOW_DEBUG_CODE
for (int count = 0; count < index; count++)
cout << fileContent[count];
#endif
fclose(stdin);
}
It seems to work just fine. I will look into vectors my next free time but for right now, I am going to continue with char array.
Thank you for your suggestions.
I would do this. It's more general to cope with any size file.
void ReadFile(char*file,char**buff,int*size){
// Open file as binary putting file position at the end
ifstream is(file,ios::binary|ios::ate);
// Get the current file position, which is the file end
*size=is.tellg();
// Put file pointer back at the start
is.seekg(0,ios::beg);
// errors
if (!*size){
cout<<"Unable to open input file or file empty\n";
exit(9);
}
// allocate a buffer one bigger to allow for zero terminator
*buff=new char[*size+1];
// read the whole file in one hit
is.read(*buff,*size);
// Done. So close and zero delimit data.
is.close();
*(*buff+*size)=0;
}
In c++ how would I read a text file containing 3 float variables not as string types, but as float variable types for re-use by a program.
I was trying to use fscanf function and having results of it only reading in the first line of the file. How do I tell it to use delimiters such as \n end of line and have it continue to process the rest of the file?
Thanks.
#include <cstdlib>
#include <math.h> //Include math functions
#include <iostream> //Stream to allow input/output
#include <fstream> //Stream class to read/write files
using namespace std;
string line = "0.0";
char str [80];
float f;
FILE * pFile;
int main () {
pFile = fopen ("C:\\Users\\Brian\\Documents\\NetBeansProjects\\CppApplication_2\\init_temps.txt","r");
fscanf (pFile, "%f", &f);
cout << f;
return 0;
}
Based on your code, it seems you are only reading the first number. You should iterate 3 times:
int i;
for(i = 0; i < 3; i++)
{
fscanf(pFile, "%f", &f);
cout << f << endl;
}
or better yet check for fscanf()'s return value to better decide if you've read it all.
On another note, you should learn to use local variables instead of global variables, unless there's really a need to.
Hope this helped.
floats.text
5.5
2.2
1.1
read.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
float sum = 0;
ifstream myfile ("floats.text");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
sum += ::atof(line.c_str());
}
myfile.close();
}
cout << sum << endl;
return 0;
}
result
./a.out
>> 8.8
im trying to count the characters inside a text file in c++, this is what i have so far, for some reason im getting 4. even thou i have 123456 characters in it. if i increase or decrease the characters i still get 4, please help and thanks in advance
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const char FileName[] = "text.txt";
int main ()
{
string line;
ifstream inMyStream (FileName);
int c;
if (inMyStream.is_open())
{
while( getline (inMyStream, line)){
cout<<line<<endl;
c++;
}
}
inMyStream.close();
system("pause");
return 0;
}
You're counting the lines.
You should count the characters. change it to:
while( getline ( inMyStream, line ) )
{
cout << line << endl;
c += line.length();
}
There are probably hundreds of ways to do that.
I believe the most efficient is:
inMyStream.seekg(0,std::ios_base::end);
std::ios_base::streampos end_pos = inMyStream.tellg();
return end_pos;
First of all, you have to init a local var, this means:
int c = 0;
instead of
int c;
I think the old and easy to understand way is to use the get() function till the end char EOF
char current_char;
if (inMyStream.is_open())
{
while(inMyStream.get(current_char)){
if(current_char == EOF)
{
break;
}
c++;
}
}
Then c will be the count of the characters
this is how i would approach the problem:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string line;
int sum=0;
ifstream inData ;
inData.open("countletters.txt");
while(!inData.eof())
{
getline(inData,line);
int numofChars= line.length();
for (unsigned int n = 0; n<line.length();n++)
{
if (line.at(n) == ' ')
{
numofChars--;
}
}
sum=numofChars+sum;
}
cout << "Number of characters: "<< sum << endl;
return 0 ;
}
Just use good old C FILE pointers:
int fileLen(std::string fileName)
{
FILE *f = fopen(fileName.c_str(), "rb");
if (f == NULL || ferror(f))
{
if (f)
fclose(f);
return -1;
}
fseek(f, 0, SEEK_END);
int len = fell(f);
fclose(f);
return len;
}
I found out this simple method , hope this helps
while(1)
{
if(txtFile.peek() == -1)
break;
c = txtFile.get();
if(c != txtFile.eof())
noOfChars++;
}
This works for sure, it is designed to read character by character.
It could be easily put into a class and you may apply function for every char, so you may check for '\n', ' ' and so on. Just have some members in your class, where they can be saved, so you may only return 0 and use methods to get what exactly you want.
#include <iostream>
#include <fstream>
#include <string>
unsigned long int count(std::string string)
{
char c;
unsigned long int cc = 0;
std::ifstream FILE;
FILE.open(string);
if (!FILE.fail())
{
while (1)
{
FILE.get(c);
if (FILE.eof()) break;
cc++; //or apply a function to work with this char..eg: analyze(c);
}
FILE.close();
}
else
{
std::cout << "Counter: Failed to open file: " << string << std::endl;
}
return cc;
};
int main()
{
std::cout << count("C:/test/ovecky.txt") << std::endl;
for (;;);
return 0;
}
C++ provides you with a simple set of functions you can use to retrieve the size of stream segment.
In your case, we want to find the file end, which can be done by using fstream::seekg, and providing the fstream::end.
note that fstream is not implementing the end iterator overload, this is it's own end constant
When we've seeked towards the end of the file, we want to get the position of the stream pointer, using tellg (also known as the character count in our case).
But we're not done yet. We need to also set the stream pointer to its original position, otherwise we'll be reading from the end of the file. Something we don't want to do.
So lets call fstream::seekg again, but this time set the position to the begining of the file using fstream::beg
std::ifstream stream(filepath);
//Seek to end of opened file
stream.seekg(0, stream.end);
int size = stream.tellg();
//reset file pointer to the beginning of the file
stream.seekg(0, stream.beg);