I have a problem with reading lines from a .txt file in C++.
The code is compiled with gmake on a FreeBSD environment.
So here is my code
int main(int argc, char **argv)
{
std::string temp_value_line;
std::string filename = "values.txt";
std::ifstream open_file(filename.c_str());
if (!open_file.is_open()) {
sys_err("Failed to load values from values.txt");
return 0;
}
int counter = 0;
while (!open_file.eof())
{
open_file >> temp_value_line;
str_to_number(common_value[counter], temp_value_line.c_str());
counter++;
}
sys_log(0, "values loaded succsefully");
open_file.close();
}
After building and running the application, there is the specified error message in my error log, so the file is not opened.
I already checked if there is a permissions or naming problem like "values.txt.txt" but everything seems to be okay. I am able to read/modify the file via console editor.
Thanks in advance.
Related
I am working on Windows and I am trying to write an array into a Ubuntu device using C++ in Visual Studio 2019. Here's a sample of my code:
int Run_WriteCalibTable(char *pcIPAddress, int iNumArgs, float *fArgs, int *iAnsSize, char *sAns)
...
...
...
char pcFolderName[256];
char pcFileName[256];
sprintf(pcFolderName, "%s\\%s",pcSavePath, pcUUTSerialNumber);
sprintf(pcFileName, "%s\\calib_rfclock.conf",pcFolderName);
// WRITE TABLE ON PC
FILE *pFileW;
pFileW = fopen(pcFileName,"wb");
fwrite(&CalibTable, sizeof(char), CalibTable.hdr.v1.u32Len, pFileW);
fclose(pFileW);
}
return 0;
However, I keep having this pop-up from Microsoft Visual C++ Debug Library that says:
Debug Assertion Failed:
Program:...
File: f:\dd\vctools\crt_bld\sefl_x86\crt\src\fwrite.c
Line: 77
Expression: (stream != NULL)
...
I found this thread and I tried logging in as root on my Ubuntu device. I also tried:
mount -o remount,rw /path/to/parent/directory
chmod 777 /path/to/parent/directory
And I can also create/edit manualy any file in the directory I'm trying to write into with my code, but I get the same error when running it.
Anyone knows what could cause this? I think it could be on the Windows side, but I don't know what I am doing wrong. Thanks a lot in advance.
You never check that opening the file succeeds - and it most likely fails, which is why you get the debug pop-up. Your use of \ as directory delimiters may be the only reason why it fails, but you should check to be sure.
I suggest that you use std::filesystem::path (C++17) to build your paths. That makes it easy to create paths in a portable way. You could also make use of a C++ standard std::ofstream to create the file. That way you don't need to close it afterwards. It closes automatically when it goes out of scope.
Example:
#include <cerrno>
#include <cstring>
#include <filesystem>
#include <fstream>
int Run_WriteCalibTable(char *pcIPAddress, int iNumArgs, float *fArgs,
int *iAnsSize, char *sAns)
{
...
// Build std::filesystem::paths:
auto pcFolderName = std::filesystem::path(pcSavePath) / pcUUTSerialNumber;
auto pcFileName = pcFolderName / "calib_rfclock.conf";
// only try to write to the file if opening the file succeeds:
if(std::ofstream pFileW(pcFileName, std::ios::binary); pFileW) {
// Successfully opened the file, now write to it:
pFileW.write(reinterpret_cast<const char*>(&CalibTable),
CalibTable.hdr.v1.u32Len);
} else {
// Opening the file failed, print the reason:
std::cerr << pcFileName << ": " << std::strerror(errno) << std::endl;
}
...
}
I'm using tinyxml through openframeworks which uses cstdio for file access. I can see the example program quite happily create and write files but there is no delete so my plan is to implement remove, but after trying to run this code in my own project it doesn't seem to create a file or notify me of an error.
This code runs as expected on windows, just not on mac osx 10.8.5, no file is generated.
#include <cstdio>
int main(int argc, const char * argv[])
{
bool bClosed = false;
bool bWritten = false;
FILE* testFile;
testFile = fopen(".\\test.xml", "w");
if(testFile)
{
bWritten = fputs("test writing.", testFile);
bClosed = !fclose(testFile);
}
return 0;
}
edit: i now know the file exists as can read from it, i just cant view it in finder, i have hidden files shown, its not found its way into the app's package contents.
On a unix-like system (e.g. Mac OS X and Linux) a Windows path as
".\\test.xml"
should rather be
"./test.xml"
Anyway the simplest solution for this case might just be
"test.xml"
I have a simple text editor in which I would like to open a file when it's double-clicked from the system file manager.
I managed to do that without any problems under Ubuntu Linux (13.04), but in Mac OS X my code did not work.
After researching a bit, I found out that you need to add the --args argument in terminal in order to parse the arguments to main().
I fixed my code and now my application bundle can open files from the terminal, but when I double click a file in Finder (and select my app), my application launches as if did not receive any terminal arguments (creates a new file).
Here is the code of the main() function:
int main(int argc, char *argv[])
{
QApplication MyApp(argc, argv);
Textpad.setApplicationName("MyApp");
Textpad.setApplicationVersion("0.7.2");
Textpad.setWindowIcon(QIcon(":/app-icon/48x48/icon.png"));
MainWindow *Window = new MainWindow();
QString Arguments;
QString FileLocation;
if (argc != 1) {
int i;
for (i = 0; i < argc; i++)
Arguments = argv[i];
// Check if the OS is Mac OS X (Mac OS X is 3)
if (Window->CheckOS() == 3)
// Remove the "--args" so that we don't confuse it with the file location
Arguments.replace("--args", "");
if (Arguments == "--help") {
// Show help
}
// Create a new file when Textpad is launched normally (under Linux)
if (Arguments == "%U") {
FileLocation.clear();
// Load settings and create UI
Window->Initialize();
// Open the requested file
Window->LoadFile(FileLocation);
}
else {
FileLocation = Arguments;
// Load settings and create UI
Window->Initialize();
// Open the requested file
Window->LoadFile(FileLocation);
}
}
else {
// Create new file
FileLocation.clear();
// Load settings and create UI
Window->Initialize();
// Open the requested file
Window->LoadFile(FileLocation);
}
return MyApp.exec();
}
As I said before my application opens files without probles from the terminal when I write the following:
open MyApp.app --args <location of my file>
But fails when I try to open a file from Finder.
What I am missing?
Thank you in advance.
First of all, you will have to link against the OX-X Framework. OSX works with Events similar to signal slots. The filename will also be given by an apple event. I`ve had this quite some time ago with another language, but i still found a reference:
Edit doc now in Qt archive:
https://doc.qt.io/archives/qq/qq12-mac-events.html
hi could someone help me i'm trying getting the liberty simpleini for c++ to read/write a file from a different directory but so far nothing is working.
using windows 7
#include "SimpleIni.h"
#include <stdio.h>
int main( int argc, char** argv)
{
CSimpleIniA ini;
ini.SetValue("test", "default", "1");
ini.SaveFile("c:\\test\\test.ini");
//tried ini.SaveFile("c:\test\test.ini");
ini.LoadFile("c:\\test\\test.ini");
//tried ini.LoadFile("c:\test\test.ini");
const char * set = ini.GetValue("test", "default", "");
printf( "value = %s", set ); // should load from c:\test\test.ini
return 0;
}
source http://code.jellycan.com/simpleini-doc/html/index.html
The problem is in that it doesn't create directories.
You should create "c:\test" directory first on your own and then start application.
I started with your code and it didn't work, then I created "test" folder on drive C and it began to.
I have a problem with a program that I'm writing. It is a command line parser that parses bencode (used in torrent files). The program accepts a filename as it's command line. When I build and run the program in Microsoft Visual Studio 10.0 using the debugging Commmand Line arguments setting to input a command line the program tells me that it failed parsing.
If I open a command prompt and run the program from the command prompt with the same command line, the program works perfectly! What's going on? Is this a common problem with Visual Studio?
I used the debugger in Visual Studio to trace where the program fails and it appears that a call to the stat function ( http://msdn.microsoft.com/en-us/library/14h5k7ff.aspx ) used to get the length of the file returns an error in Visual Studio but works fine when run outside of Visual Studio.
The Code uses a Bencode parser which can be found here: http://funzix.git.sourceforge.net/git/gitweb.cgi?p=funzix/funzix;a=blob;f=bencode/bencode.c
And here is the code for the program:
#include <stdio.h>
#include "../Parse/bencode.h"
int main(int argc, char *argv[]){
if(argc != 2){
printf("Usage: whirlwind filename\n");
return 1;
}
char *buf;
long long len;
be_node *n;
//read the torrent file into a buffer and store at &buf
buf = read_file(argv[1], &len);
if(!buf){
buf = argv[1];
len = strlen(argv[1]);
}
printf("Decoding: %s\n", argv[1]);
n = be_decoden(buf, len);
if(!n){
printf("Parsing failed!\n");
return 1;
}
if(n->type != BE_DICT){
printf("This file is not a valid Bencoded Dictionary.\n");
return 1;
}
int i;
char* keyName;
for(i = 0; i < 10; i++){
keyName = n->val.d[i].key;
if(keyName == "announce"){
printf("\n\n");
}
printf("%s\n", keyName);
if(keyName == "announce"){
printf("\n\n");
}
}
return 0;
}
If you pass a relative path from Visual Studio you should be sure that it resolves correctly when your app runs inside the IDE. This problem arises because, when debugging, the current directory is usually \bin\debug.
To be on the safe side put a full pathname or read the location of your file from a configuration file.