Not able to read data from the file in xcode - c++

I am a beginner c++ programmer and I was accustomed to using Visual Studio before, but i am now using mac and i use xcode now. In xcode, i am not able to read data from the file (so i am also not able to get the output.) Which setting should i change in xcode to read data from the file(the file is in the same folder as the project) properly ?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//in thefile.txt i only have a string "hello"
int main() {
string text; //since i only have a string in the file. So this is a variable representation for it
ifstream myfile;
myfile.open("thefile.txt");
myfile >> text; //extract the word from the file
cout << "The following is the data in the file: " << text <<endl; //trying to print The following is the data in the file: hello
return 0;
}
//Output is "The following is the data in the file: "

Probably the most straightforward way is to use a fully qualified file name to take the guesswork out of it. If you're not sure of the full name, you can open up a window in the OS X Terminal program, type "file ", and then drag your file from a Finder window onto that command line. Terminal will fill in the full path. "file" is an innocuous command that will tell you information about your file type. But the important thing is, you will have a full path that you can then copy from Terminal and paste into your code.
If your file path has blanks in it, you may have to manually remove the backslash characters that will appear.
Xcode doesn't have a setting per se (that I know of) to determine what directory is active when you launch your program. But a full path takes the guesswork out of it.

Related

Is there a way to move the cursor to the end of a text file when opened on windows?

I am writing to a text file using c++ and using a batch file to open the text file and then run the corresponding exe file at the same time. My c++ code is writing a dividing underscore line and the current date and then the user would write whatever text. The issue is that when I run the batch file which opens the text file, the cursor is at the beginning of the file and I want it to start at the very end so I wouldn't have to move it myself to write text.
This is my c++ code:
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <vector>
using namespace std;
string underscoreDiv (int lengthText){
string underscores;
for(int i{}; i<lengthText; i++)
{
underscores += "_";
}
return underscores + "\n";
}
struct Date
{
int year;
int month;
int day;
Date()
{
time_t t = time(0);
tm* now = localtime(&t);
year = now->tm_year + 1900;
month = now->tm_mon + 1;
day = now->tm_mday;
}
};
int main(){
fstream fileApp("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::in | ios::app);
if(fileApp.is_open()){
string line;
string underscore;
Date date;
int count[2]={0};
underscore=underscoreDiv (80);
fileApp.clear();
fileApp<<"\n";
fileApp<<underscore<<"\n";
fileApp<<date.month<<"/"<<date.day<<"/"<<date.year<<" : ";
fileApp.clear();
fileApp.close();
}
else{
cout<<"Text file not found";
}
system("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt");
return 0;
}
Here is my batch file
start /b C:\Users\trist\OneDrive\Desktop\projects\notes_project_app\app_proj.exe
start C:\Users\trist\OneDrive\Documents\Notes_application\Notes_app.txt
'I tried playing with the c++ code but I'm finding it hasn't been able to actually move the cursor position when the file is opened through windows. I'm having trouble trying to move the cursor to the end through the batch file. I tried doing a send key page down but I couldn't get that to work either.'
There may be some unnecessary function in the code as I'm trying to other things meanwhile.
Mmmm... Your question is pretty confusing... After read it several times, I think I can state these points:
Neither Windows nor a Batch file "open" a text file. A text file is open by a text editor program (like Windows Notepad). If I correctly understand your question, you have a C++ program that create a text file and then, after the file was created, open the text file with the standard text editor, not at "the same time". For this reason, your batch file is wrong: if both your C++ program and text editor run at the same time (both started via start command), then exist the possibility that Notepad open the file before the C++ program have completed and closed it (not matter if the start command of the C++ program is placed before the start command of Notepad).
On the other hand, you just want to open the text file (with the standard text editor) and place the cursor at the very end of the file, right? In such a case no matter who and how created the text file! So all your explanation about your C++ code (and the C++ code itself) have no relation with your problem and just confuse and over-complicate the problem...
However, in this case the C++ code show another error: it open the text file via a system command! The batch file also open the file, so the system command in the C++ code is wrong and must be deleted.
I think this Batch file will solve your problem:
#if (#CodeSection == #Batch) #then
#echo off
rem Run the C++ program, do *NOT* use "start" here
C:\Users\trist\OneDrive\Desktop\projects\notes_project_app\app_proj.exe
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start the text editor program ("open" the text file)
start C:\Users\trist\OneDrive\Documents\Notes_application\Notes_app.txt
rem Wait a little
timeout /T 1
rem Send a Ctrl-End key to move cursor to end of the file
%SendKeys% "^{END}"
goto :EOF
#end
// JScript section
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
For further details about the method to send a key from the Batch file, read this answer.

cannot create a text file in C++

I'm using an ofstream object to create and print a string to a text file, but it doesn't work. this is my code :
#include <iostream>
#include <fstream>
using namesace std;
int main()
{
ofstream output("d:\\data.txt");
output << "this is my text" << endl;
output.close();
return 0;
}
The file data.txt was created when I set output("data.txt"). The text file was created in the same folder that contains the source code. But when I set output(d:\\data.txt) or any other location, it was not created at all. This code has also worked well in other computer and the problem only occurs in my laptop. I'm using visual stdio 2013 and operated by
Windows 10 pro.
Try making a file manually in d:\\, then get the complete, correct directory of the file from its properties. That way, you will know any mistakes you are making in specifying the directory of the file to be created.

unable to open file stream c++

I am working with Xcode and I am having trouble opening a file stream to assign variables from a text file. I speculate that placing the txt file in the same directory as the project would allow me open the stream without including the entire dir. I have been messing with this for a little while to no avail can I get it to work properly. I believe I was able to read data at one point, but I think the string printed was in unicode (not sure). It is a very simple program.. I would think that it would work.
I think my problem has to do with the directory the example is in and how Xcode works with project files. I just put the example file in the project folder and hoped that it would work.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string name;
ifstream infile;
infile.open("example.txt");
if(infile.is_open())
{
infile >> name;
}
else
cout << "Unable to open file";
cout << name;
return 0;
}
First of all, remember, that working directory is not always the same directory where the program's binary resides.
Change:
infile.open("example.txt");
to:
infile.open("/full/path/to/program/directory/example.txt");
where /full/path/to/program/directory/ is the location of folder, where program (and thus example.txt file) is placed. It should fix the issue.
By the way, you may also want to read this question, that addresses very similar problem.
Also, read about getcwd() function.

Can't get a simple ifstream to work in Visual Studio Express

I am trying to learn C++ and am on the file input/output section. I've hit a brick wall because my test application just plainly isn't working in Visual Studio Express 2012. Here is my code:
// ConsoleApp03.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream file_reader;
file_reader.open("C:\temp.txt");
// Test to see if the file was opened
if (!file_reader.is_open() ) {
cout << "Could not open file!" << endl;
return 255;
}
string line;
// Read the entire file and display it to the user;
while (getline(file_reader,line)) {
cout << line << endl;
}
// Close the file
file_reader.close();
return 0;
}
Every time I run this, I get "Could not open file!". I have verified that the file being opened does exist, and I have sufficient permission to read. I have tried other text files, including in other different locations like my documents folder, but the result is always the same. My text file is very simple and only contains two lines of text. I am abel to open this file in Notepad++, and the file has no special attributes (system, Read only, etc). I have even tried converting the file to/from ANSI and UTF-8 with no luck.
I have looked at other problems similar to what I have here, but these don't seem to be applicable to me (e.g.: ifstream::open not working in Visual Studio debug mode and ifstream failing to open)
Just to show how simple the text file is, here is me typing it from the command prompt:
C:\>type C:\temp.txt
Hi
There
This may or may not fix your problem, but \ followed by char is an escape sequence. So your file path is actually invalid. Try
file_reader.open("C:\\temp.txt");
The \t actually means tab. See here.

How to create a text file in a folder on the desktop

I have a problem in my project. There is a project folder on my desktop. I want to create a text file and write something include this text file. That is my code:
ofstream example("/Users/sample/Desktop/save.txt");
But I want to it could been run the other mac. I don't know what I should write addres for save.txt.
Can anyone help me?
Create a file and write some text to it is simple, here is a sample code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
std::ofstream o("/Users/sample/Desktop/save.txt");
o << "Hello, World\n" << std::endl;
return 0;
}
I hope that answers your question but I am not sure if i understand your question correctly, If not please add the details correctly of what you are trying to acheive.
[Update]:
Okay I guess the comment clears the problem.
Your real question is, You want to save the file in the desktop of the user who is playing the game. So getting the path of the current user's desktop is the problem.
I am not sure if there is an portable way to get desktop path but it can be done in following ways:
In Windows:
Using the SHGetSpecialFolderPath() function.
Sample code:
char saveLocation[MAX_PATH] = {0};
SHGetSpecialFolderPath(NULL, saveLocation, CSIDL_DESKTOPDIRECTORY, FALSE);
//Now saveLocation contains the path to the desktop
//Append your file name to it
strcat(saveLocation,"\\save.txt");
ofstream o(saveLocation);
In Linux:
By using environment variables $HOME
sample code:
string path(getenv("HOME"));
path += "/Desktop/save.txt";
ofstream o(path);
Rules defining where-you-should-save-file vary from platform to platform. One option would be to have it part of your compile script (that is you #define SAVEGAME_PATH as part of your compilation configuration), and thus your code itself remain more platform-agnostic.
The alternative is to find a save-data-management library that is already designed to be ported across different platforms. Whether it'd be a C or C++ or whatever-binary-interoperable library then no longer matters.
Just don't expect that to be part of C++ (the language).
if you want your program to run across platform,you'd better use the
relative path.
eg. "./output.txt",or better “GetSystemDirectory()”to obtain the system
directory to create a file,and then you could write or read the file
with the same path..