Xcode reading chars from file in c++ - c++

I have the following code to read a character from a file:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, const char * argv[])
{
ifstream f("text.txt");
char c;
f.get(c);
cout << c << endl;
return 0;
}
and my text.txt file contains:
hello world!
However, when I run this on Xcode, I get an inverted question mark as the output.
It works fine on terminal, but not on Xcode. Does anyone know why this happens?
I'm using Xcode to debug some code, but I cant do that anymore because this problem is causing a lot of other errors in my program.

Your text.txt file will not be at the executable path.
Go to your Build Phases - > Copy Files -> Add Your text file
Make sure that:
Destination should be Products Directory
Copy only when installing should be unchecked

Related

Why won't header file change the contents?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream archivo("saludos.txt",ios::in|ios::out); // Abrir y Leer
char caract;
int cont=0;
while (!archivo.eof())
{
archivo.seekg(cont,ios::beg);
caract=archivo.get();
if (caract=='A')
{
archivo.seekp(cont,ios::beg);
archivo<< 'O';
}
cont++;
}
archivo.close ();
}
i'm using this code but when i build and run it, nothing happens in the file saludos.txt There isn't even a response on the console application. anybody know why? i'm using codeblocks and i also have #include fstream
I tried your code in my environment and it works just fine, it replace all 'A' characters with '0'.
I think your problem is with Codeblocks, if you create a new project and want to use file with the relative path in your project, you have to go to Project -> Properties -> Build targets and change the "Executing Working Dir" to your project's folder.
Or you cant try with a absolute file name with full system path first.

How to use file strings as commands in c++

I am trying to make a program on Windows 10 using Visual Studio 2015 that would sim-link certain files to certain locations. I am trying to make a text file with the location of the files, and the sim-link destination to use.
This is an example of the file data that would be in the properties.txt file:
FileLocation: "Z:\Folder\file.txt"
FileMkdirLocation: "Z:\Folder2\file.txt"
I want to use something like system(mkdir "sim-link_file_location" "file_location") by changing the data that is in properties.txt. I want to be able to add more than 1 file, without recompiling the program and writing each command for each file, one by one.
The problem is that I don't know how to make the commands use the data in the file.
EDIT: I managed to find out a way, but I get errors when compiling the program. I use this code:
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
using namespace std;
//initialization of Properties File used
ifstream PropertiesFile ("PropertiesFile.txt");
int main()
{
//initialization of variables used
int input_option;
char FileLocation[256], Command[]="mklink ";
// string FileLocation, Command;
PropertiesFile >> FileLocation;
/* switch (input_option)
{
case "add all mods":
}
*/
cout << "FileLocation: " << FileLocation;
cout << endl;
strcat(Command, FileLocation);
Command[strlen(FileLocation)] = '\0';
cout << Command;
cout << endl;
//system(command);
system("pause");
return 0;
}
I know that i haven't used all variables yet.
It tells me that "strcat" is deprecated and to use "strcat_s" instead, and when i replace it with that, I get
"Debug Assertion Failed - Expression: (L"Buffer is too small" && 0)"
I had to make the "Command" char bigger than "FileLocation" because then strcat_s would not be able to copy the content. After that the program worked fine, and there were no other Assert Errors.
The command to create a soft link in linux is: ln -s <source> <destination>
You can use this in a system(""); call, BUT before you continue in your code, you will have to make sure that the kernel finished executing this command.
After that you can read the link as if it was the original file.

Cannot open file with relative path? (C++ ifstream)

I know this seems like a simple question, but I tried everything I can think of to no avail to something that shouldn't have been a problem in the first place.
This is a small C++ program that opens a file. When I open it with its absolute filepath, it works fine. With a relative path, however, it stops working.
Here's the file path of the program and the files I'm trying to read:
C++ program: "/Users/Baggio/C++/Lab0/Lab0/Lab0/main.cpp"
Files: /Users/Baggio/C++/Lab0/Lab0/Lab0/result.txt, /Users/Baggio/C++/Lab0/Lab0/Lab0/dict.txt
Here's the code snippet:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
int main(int argc, const char * argv[]) {
// string dict_filename = "/Users/Baggio/C++/Lab0/Lab0/Lab0/dict.txt";
// string result_filename = "/Users/Baggio/C++/Lab0/Lab0/Lab0/result.txt";
string dict_filename_string = "dict.txt";
string result_filename_string = "result.txt";
const char* dict_filename = dict_filename_string.c_str();
const char* result_filename = result_filename_string.c_str();
// open files
ifstream dict_file(dict_filename, ifstream::in);
ifstream result_file(result_filename, ifstream::in);
if (!dict_file || !result_file) {
cerr << "File could not be opened." << endl;
exit(1);
}
}
Result of execution
File could not be opened.
I'm sure I've done all the includes right, and the data types right for the ifstream constructor arguments. The only thing I can think of worth mentioning is the system I'm on: I'm on a Mac and I'm using XCode6 as my IDE.
Also, I've tried to move the files' location (results.txt and dict.txt) to these locations to no avail:
/Users/Baggio/C++/Lab0/Lab0/Lab0/
/Users/Baggio/C++/Lab0/Lab0/
/Users/Baggio/C++/Lab0/
/Users/Baggio/C++/
Thanks for your help guys!! Any suggestions or thoughts appreciated.
Print out your current working directory when you run the program:
char buffer[256];
char *val = getcwd(buffer, sizeof(buffer));
if (val) {
std::cout << buffer << std::endl;
}
This will tell you where you are running your program from and thus why the path doesn't match for relative paths. A relative path is relative to the current working directory, not to where your binary is located.
If you want to make the path relative to the location of the binary then you will have to do that yourself. Many programming languages offer this as an option, but it is not built-in to C++. You can do this by finding the executable using the argv[0] from main. Then you need to drop the file component of the executable path and replace it with the file name that you are interested in.
Since C++17, you can use std::filesystem::current_path() instead of getcwd.
std::cout << std::filesystem::current_path() << std::endl;

Problems using .open with ifsteam objects

The best way to explain my problem is probably just to show you my code, because it's as simple as it gets.
#include <iostream>
#include <fstream>
int main (int argc, const char * argv[])
{
std::ifstream in;
std::string line;
in.open("test.txt");
if (in.fail()) std::cout << "failed. \n";
getline(in, line);
std::cout << line;
return 0;
}
So when I run this, console is returning "failed." instead of opening up the file called test.txt — which is in the same folder as my .xcodeproj file and is also displayed in my Xcode navigator.
I'm not sure what I'm misunderstanding about this process, but I suspect it will be something simple.
Thanks! :)
The file is in the same directory as your .xcodeproj file? Well, there's your problem right here.
By default, the working directory of a process launched from Xcode will be the output directory (that is, the directory where the program is). Depending on your Xcode version, it's probably going to be in <Project Directory>/build/Debug.
Try moving the file there.

How do I run my code from the command line?

i have following code
#include <iostream>
using namespace std;
int main(int argc,char arg[]){
int a=arg[1];
int b=arg[2];
int c=a+b;
cout<<c<<endl;
return 0;
}
i am using windows 7 microsoft visual c++ 2010
how run it from command line?
Open a command prompt from the Start Menu. Use the CD command to change directories to where your exe is. type the name of your exe followed by the arguments.
foo.exe 1 2
or just
foo 1 2
Expect the output (once you've fixed your numerous code errors):
3
Once you compile this you get an executable. Navigate to the directory containing the executable and run it.
Go to google and look for a windows console tutorial. You need to start it from the console. Alternatively you can assign command line in the project properties. I'd recommend learning to do both.
BTW, this code almost certainly does not do what you think it does.
The compiled output of your program will be in the Debug or Release folder inside the solution folder (at least with default project settings). Just change to that directory and run the .exe file.
Open the Visual Studio Command Prompt (you can find it in the Start Menu)
cd to your source file directory
type:
cl.exe <your file name>.cpp
It will create a file .exe
Once your code is setup properly it would be something like this.
MyApp 2 3
Or similar
Navigate to the directory where the executable (.exe) is located. Then type the executable's name followed by two integer parameters.
C:\TestProg\> TestProg 5 6
The problems in your original example are corrected here:
#include <iostream>
#include <sstream>
int main(int argc, char *arg[])
{
std::stringstream sa;
std::stringstream sb;
int a;
int b;
int c;
if (argc >= 3)
{
// Convert string parameter into an integer.
sa.str(arg[1]);
sa >> a;
if (!sa)
{
return 1; // error
}
// Convert string parameter into an integer.
sb.str(arg[2]);
sb >> b;
if (!sb)
{
return 1; // error
}
}
else
{
return 1; // error
}
c = a + b;
std::cout << c << std::endl;
return 0;
}