How to create a function: Get a single value from SD card file using the file name as function parameter - c++

I appreciate any guidance or help I can get on this. I am writing a program with values for a PID stored on an SD card so I can change them on the touchscreen without the need to hook it up to my computer. I want a single function that I can call with parameters allowing me to increase or decrease the number and change the file name. The below function is what I have to change whether "pnum.txt" increases or decreases; however I cannot figure out how to make a File work as a parameter.
I have tried making " "pnum.txt" " (with quotes) as a char and as a String, and even though it prints out as it should, it doesn't work when inserted into the function. I have also tried passing the whole SD.open("pnum.txt", FILE_WRITE) and myFile = SD.open("pnum.txt", FILE_WRITE) as a File, but that does something odd - it will create the file when I open it, but it won't write to the file. I'm finding myself just trying the same things over and over, so I clearly have a lack of understanding that I'm not finding anywhere. Thank you again for any help on this!
float incDecValue(float value) {
//This is important, because the libraries are sharing pins
pinMode(XM, OUTPUT);
pinMode(YP, OUTPUT);
value;
SD.remove("pnum.txt");
myFile = SD.open("pnum.txt", FILE_WRITE);
myFile.print(value);
myFile.close();
counter = 0;
myFile = SD.open("pnum.txt");
if (myFile) {
while (myFile.available()) {
testChar[counter] = myFile.read();
counter++;
}
myFile.close();
}
float convertedValue = atof(testChar);
return convertedValue;
}
And I will call it like this.
pValue = incValue(pValue+=.5);

As not exactly knowing what you really want I did the following assumptions:
You want to save a single float value to a file called pnum.txt
You want to do something with that value
You want the processed value to write back to the file pnum.txt (overwriting the content)
Two different functions parametrized each with fileName as input and the value for write
So here a complete sequence (works as posted) you could easily implement into your code. No String class is used and its a one line file read/write only:
/* SD card pid read/write
The circuit:
SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4 */
#include <SPI.h>
#include <SD.h>
const uint8_t chipSelect = 4;
char dataChar[16] = {'\0'};
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
}
Serial.print("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed or no card present");
return;
}
Serial.println("Card initialized");
}
void loop() {
float pValue = readFileValue ("pnum.txt") + 0.5;
writeFileValue ("pnum.txt", pValue);
}
float readFileValue (const char* fileName) {
/* Open the file. note that only one file can be open at a time,
so you have to close this one before opening another.*/
File dataFile = SD.open(fileName, FILE_READ);
// if the file is available, write to it:
if (dataFile) {
char c;
uint8_t i = 0;
while (dataFile.available()) {
c = dataFile.read(); // Read char by char
if (c != '\n') { // As long no line terminator
dataChar[i] = c;
i++;
}
else {
dataChar[i] = '\0'; // Terminate char array properly
dataFile.close();
break;
}
}
Serial.print("Success writing content: ");
Serial.println(dataChar);
}
else { // If the file isn't open, pop up an error:
Serial.print("Error opening requested file: ");
Serial.println(fileName);
}
float fileVal = atof(dataChar);;
return fileVal;
}
bool writeFileValue (const char* fileName, float fileVal) {
SD.remove(fileName); // Delete the existing file if existing
File dataFile = SD.open(fileName, FILE_WRITE);
// If the file opened okay, write to it
if (dataFile) {
// dtostrf(floatvar, StringLengthIncDecimalPoint, numVarsAfterDecimal, charbuf);
dtostrf(fileVal, 5, 2, dataChar); // Not really needed for this simple issue, but ..
Serial.print("Writing to file: ");
Serial.println(fileName);
dataFile.println(dataChar);
// Close the file
dataFile.close();
Serial.println("Success saving done");
return true;
} else {
// if the file didn't open, print an error:
Serial.println("Error opening file: ");
Serial.println(fileName);
return false;
}
}

Related

Unable to open file in bytes from sd card (ESP32)

I want to open a .wav file in bytes from the sd card connected to esp32.
My code is based in this question
I just want upload a file from my sd card to a server but by the moment I can't read the file despites the file exists in the sd card:
Look this lines of code:
char *fname = "/sdcard/test.wav";
FILE *fp = fopen(fname, "rb"); // read in bytes
if(!fp) {
Serial.println("File doens't exist");
}
I don't understand why it File file = SD.open("/test.wav") works but the above code not. According to my reference I should read this file in bytes and not in a normal manner like this => File file = SD.open("/test.wav").
I would like know how I can see the full path of my sd card because the original code uses this:
char *fname = "/sdcard/test_text.txt";
FILE *fp = fopen(fname, "rb");
why that uses this path /sdcard/test_text.txt I don't know exactly. If I try to open by using:
File file = SD.open("/test.wav")
will works but some lines of code after this will throws errors because the file should be read in bytes.
I would like to see your advices guys I will appreciate any idea to fix this problem.
this is the entire code:
#include "Arduino.h"
#include "WiFi.h"
#include "SD.h"
#include "FS.h"
#include "HTTPClient.h"
//SD CARD MODULE
#define SD_CS 5
#define SPI_MOSI 23
#define SPI_MISO 19
#define SPI_SCK 18
// Wifi Credentials
const char* ssid = "XXX";
const char* password = "XXX";
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("MY IP address: ");
Serial.println(WiFi.localIP());
if (!SD.begin(SD_CS)) {
Serial.println("SD init failed!");
return;
}
Serial.println("SD init successfull!");
}
void loop()
{
WiFiClient client;
Serial.println("starting file upload");
IPAddress host(192, 168, 18, 8); //server ip
int port = 80;
if (!client.connect(host, port))
{ // check connection to host if untrue internet connection could be down
Serial.println("couldn't connect to host");
}
Serial.println("Connect to host!");
HTTPClient http;
const char* serverName = "http://192.168.18.8/upload/upload.php";
http.begin(client, serverName);
char *fname = "/sdcard/test.wav";
FILE *fp = fopen(fname, "rb"); // read in bytes
if(!fp) {
Serial.println("File doens't exist");
}
//get file size
fseek(fp, 0, SEEK_END); //send file pointer to end of file
int file_size = ftell(fp); //get end position of file
fseek(fp, 0, SEEK_SET); //send pointer back to start
int max_upload_size = 10; // array size, larger = less uploads but too large can cause memory issues
int num_of_uploads = file_size / max_upload_size; // figure out how many evenly sized upload chunks we need
int num_of_uploads_mod = file_size % max_upload_size; //find out size of remaining upload chunk if needed
int i;
//upload file in even chunks
if (num_of_uploads > 0)
{
char buff1[max_upload_size+1] = {}; // array to save file too. add 1 for end of array symbol '\n'
for (i = 0; i < num_of_uploads; i++)
{
fread(buff1, sizeof(buff1)-1, 1, fp); // -1 as don't want to count the '\n'
http.addHeader("file_name", "file_name"); //header to say what the file name is
int httpResponseCode = http.POST((uint8_t *)buff1, sizeof(buff1)-1); //send data. Datatype is (uint8_t *)
}
}
//upload any remaining data
if (num_of_uploads_mod > 0)
{
int remainder = file_size - num_of_uploads * max_upload_size;
uint8_t buff2[remainder] = {};
fread(buff2, sizeof *buff2, sizeof buff2 / sizeof *buff2, fp);
http.addHeader("file_name", "file_name");
http.addHeader("Content-Type", "application/octet-stream");
int httpResponseCode = http.POST(buff2, sizeof(buff2));
}
http.end(); // Close connection
delay(10 * 1000);
}
thanks so much.
Unfortunately, this isn't straight-forward. You can either use the SD component directly or mount the correct file system driver (typically FatFs for an SD card). To use fopen, you need to register the correct driver first, hints can be found here: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/storage/fatfs.html#using-fatfs-with-vfs-and-sd-cards
I haven't tried this myself yet, but the magic function seems to be esp_vfs_fat_sdspi_mount that should enable the use of fopen with the SD card over SPI. The official documentation lacks a real-world example, but you might find something in this thread or via your preferred search engine. For further help, you might want to ask a question on arduino.se instead, where a number of experienced ESP32 experts are present.
I struggled myself with using SD Cards (fat32) on my ESP32.
When trying to open my file using
std::ofstream dataFile("/sdcard/data.json", std::ofstream::out);
It wouldn't create my file. a sys/stat would thus give a -1. Turned out that you really need to use the 8.3 naming convention for FAT32. There's no "MS windows-magic" That abbreviates the file to: sdcard.j~1 etc. So just use a correct file name. not "/sdcard/mylomgfilename.exotic_extention" but just a "/mpoint/12345678.123" filename like "/sdcard/data.txt".

XRAD'S How to get last line of SD data file?

My SD data file does not have a set 'line' limit, nor does it have data of fixed lengths on each 'line.'
Is there a way to read the SD data file to the last 'line' AND then only Serial.print() just that last 'line'?
That last line of SD data is going to be used as the first 'home' coordinate in a GPS tracker if one was to continue a journey from last location.....
even if I add white space to make the first and second saved values XXXXXX (999999), I still am not sure how to find JUST the last line in an SD data file of an unknown length...(trying to keep the SD file as ONE file, not of fixed length)
//teensy 4.1 with BUILTIN_SDCARD
#include <SD.h>
File myFile;
String buffer;//buffer to redraw saved SD data
void lastLine()
{
//myFile = SD.open ("GPS", O_APPEND);
myFile = SD.open("GPS");
while (myFile.available()) {
if (myFile) {
buffer = myFile.readStringUntil('\n');
//either from the buffer or SD I would like to
//just read the last line of the file
Serial.println(buffer);
//Serial.println(myFile.size());
}
}
}
void setup()
{
Serial.begin(9600);
Serial.print("Initializing SD card...");
if (!SD.begin(BUILTIN_SDCARD)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// open the file.
myFile = SD.open("GPS", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to GPS...");
//GPS device / code continually writes data to SD
//but using this below for brevity/debugging
myFile.println("123, 144");//these stand for the x/y data values
myFile.println("1424, 254");//and the length of x/y may go as high
myFile.println("11235, 333");//as x= 999,999, y = 999,999 etc...
//etc..for hundreds/thousands of 'lines'
// close the file:
myFile.close();
Serial.println("done.");
}
lastLine();//just read the LAST line of SD data...
}
void loop()
{
// nothing happens after setup
}
EDIT: Thank you for ideas! OK ..so i tried your suggestions I think. I can get a counter going (first step) but it only increments to 20! I'm confused as to why/how this happens.....
here is my current code. Even though there are 50 'lines' in the SD file, I'm only reading 20 (get to sizeof())....IF I change the code to print ALL the lines to serial, it won't count lines....and IF there are LESS than 20 lines, serial monitor adds empty lines until '20' is reached..
and sizeof(myFile) is also 20..not sure why
//teensy 4.1 with BUILTIN_SDCARD
#include <SD.h>
File myFile;
int counter = 0;
String buffer;//buffer to redraw saved SD data
void lastLine()
{
//myFile = SD.open ("GPS", O_APPEND);
myFile = SD.open("GPS");
while (myFile.available()) {
for (int i = 0; i < sizeof(myFile); i++) {
String line = myFile.readStringUntil('\n');
buffer = myFile.readStringUntil('\n');
const char* listConv = line.c_str();
Serial.print ("line: ");
Serial.println (line);
counter ++;
}
if (counter == sizeof(myFile)) {
Serial.print ("Done. Counter: ");
Serial.println (counter);
Serial.print ("sizeof myFile: ");
Serial.println (sizeof(myFile));
myFile.close();
counter = 0;
}
}
}
//buffer = myFile.readStringUntil('\n');
//either from the buffer or SD I would like to
//just read the last line of the file
//Serial.println(buffer);
//Serial.println(myFile.size());
void setup()
{
Serial.begin(9600);
Serial.print("Initializing SD card...");
if (!SD.begin(BUILTIN_SDCARD)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
// open the file.
myFile = SD.open("GPS", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to GPS...");
//GPS device / code continually writes data to SD
//but using this below for brevity/debugging
myFile.println("123, 144");//these stand for the x/y data values
myFile.println("1424, 254");//and the length of x/y may go as high
myFile.println("11235, 333");//as x= 999,999, y = 999,999 etc...
//etc..for hundreds/thousands of 'lines'
// close the file:
myFile.close();
Serial.println("done.");
}
lastLine();//just read the LAST line of SD data...
}
void loop()
{
// nothing happens after setup
}
ok so with some rewriting, I can now count to last file line using:
while (myFile.available()) {
for (int i = 0; i < sizeof(myFile.available()); i++) {
String line = myFile.readStringUntil('\n');
Serial.print ("line: ");
Serial.println (line);
counter ++;
Serial.print ("Counter: ");
Serial.println (counter);
if (counter == 400) {//testing different lines, works...
Serial.print ("Last Line: ");//prints the line at counter 'x'
Serial.println (line);
}
}
}
next step is to grab that last line after calculating the 'maximum' number of lines (minus a few that don't hold data I need at the end of the SD file).....
It was a bug in the library. conflict between SDFat, adafruit fork, and arduino SD. Had to delete all SD libs and reload....
working now...

Alt, Course, and Speed not displaying on the LCD display

I wrote this code for my bike computer; however, the Alt, Course, and Speed are not displaying on the LCD display although it is on the Serial monitor. The GPS module isn't returning values either.
/* BaldwinOS by John Seong
An Open-Source Project
Version 1.0
*/
#include <SPI.h>
#include <SD.h>
#include <TinyGPS++.h> // Include the TinyGPS++ library
#include <Wire.h>
TinyGPSPlus tinyGPS; // Create a TinyGPSPlus object
#define ARDUINO_USD_CS 10 // uSD card CS pin (pin 10 on SparkFun GPS Logger Shield)
/////////////////////////
// Log File Defintions //
/////////////////////////
// Keep in mind, the SD library has max file name lengths of 8.3 - 8 char prefix,
// and a 3 char suffix.
// Our log files are called "gpslogXX.csv, so "gpslog99.csv" is our max file.
#define LOG_FILE_PREFIX "gpslog" // Name of the log file.
#define MAX_LOG_FILES 100 // Number of log files that can be made
#define LOG_FILE_SUFFIX "csv" // Suffix of the log file
char logFileName[13]; // Char string to store the log file name
// Data to be logged:
#define LOG_COLUMN_COUNT 8
char * log_col_names[LOG_COLUMN_COUNT] = {
"longitude", "latitude", "altitude", "speed", "course", "date", "time", "satellites"
}; // log_col_names is printed at the top of the file.
//////////////////////
// Log Rate Control //
//////////////////////
#define LOG_RATE 5000 // Log every 5 seconds
unsigned long lastLog = 0; // Global var to keep of last time we logged
#define GPS_BAUD 9600 // GPS module baud rate. GP3906 defaults to 9600.
#define SerLCD_Address 0x72
#include <SoftwareSerial.h>
#define ARDUINO_GPS_RX 9 // GPS TX, Arduino RX pin
#define ARDUINO_GPS_TX 8 // GPS RX, Arduino TX pin
SoftwareSerial ssGPS(ARDUINO_GPS_TX, ARDUINO_GPS_RX); // Create a SoftwareSerial
#define gpsPort ssGPS
#define SerialMonitor Serial
const int statusLED = 9;
const int blueLeftLED = 8;
const int redLeftLED = 7;
const int blueRightLED = 0;
const int redRightLED = 3;
const int leftButton = A3;
const int rightButton = 11;
const int modeButton = 12;
const int buzzer = 13;
void setup() {
SerialMonitor.begin(9600);
gpsPort.begin(GPS_BAUD);
SerialMonitor.println("Setting up SD card.");
// see if the card is present and can be initialized:
if (!SD.begin(ARDUINO_USD_CS))
{
SerialMonitor.println("Error initializing SD card.");
}
updateFileName(); // Each time we start, create a new file, increment the number
printHeader(); // Print a header at the top of the new file
Wire.begin();
Wire.setClock(400000);
Wire.beginTransmission(SerLCD_Address);
Wire.write('|'); // Put LCD into setting mode
Wire.write('-'); // Send clear display command
Wire.write('|'); // Put LCD into setting mode
Wire.write('+'); // Send the Set RGB command
Wire.write(0xFF); // Send the red value
Wire.write(0x00); // Send the green value
Wire.write(0x00); // Send the blue value
Wire.println("Welcome to");
Wire.print("BaldwinOS!");
Wire.endTransmission();
delay(2000);
}
void loop() {
Wire.beginTransmission(SerLCD_Address);
Wire.write('|'); // Put LCD into setting mode
Wire.write('-'); // Send clear display command
Wire.println("Pathfinder");
Wire.print("Bike Computer");
if ((lastLog + LOG_RATE) <= millis())
{ // If it's been LOG_RATE milliseconds since the last log:
if (tinyGPS.location.isUpdated()) // If the GPS data is vaild
{
if (logGPSData()) // Log the GPS data
{
SerialMonitor.println("GPS logged."); // Print a debug message
lastLog = millis(); // Update the lastLog variable
}
else // If we failed to log GPS
{ // Print an error, don't update lastLog
SerialMonitor.println("Failed to log new GPS data.");
}
}
else // If GPS data isn't valid
{
// Print a debug message. Maybe we don't have enough satellites yet.
SerialMonitor.print("No GPS data. Sats: ");
SerialMonitor.println(tinyGPS.satellites.value());
}
}
printStats1();
smartDelay(1000);
}
byte logGPSData()
{
File logFile = SD.open(logFileName, FILE_WRITE); // Open the log file
if (logFile)
{ // Print longitude, latitude, altitude (in feet), speed (in mph), course
// in (degrees), date, time, and number of satellites.
logFile.print(tinyGPS.location.lng(), 6);
logFile.print(',');
logFile.print(tinyGPS.location.lat(), 6);
logFile.print(',');
logFile.print(tinyGPS.altitude.feet(), 1);
logFile.print(',');
logFile.print(tinyGPS.speed.mph(), 1);
logFile.print(',');
logFile.print(tinyGPS.course.deg(), 1);
logFile.print(',');
logFile.print(tinyGPS.date.value());
logFile.print(',');
logFile.print(tinyGPS.time.value());
logFile.print(',');
logFile.print(tinyGPS.satellites.value());
logFile.println();
logFile.close();
return 1; // Return success
}
return 0; // If we failed to open the file, return fail
}
void printHeader()
{
File logFile = SD.open(logFileName, FILE_WRITE); // Open the log file
if (logFile) // If the log file opened, print our column names to the file
{
int i = 0;
for (; i < LOG_COLUMN_COUNT; i++)
{
logFile.print(log_col_names[i]);
if (i < LOG_COLUMN_COUNT - 1) // If it's anything but the last column
logFile.print(','); // print a comma
else // If it's the last column
logFile.println(); // print a new line
}
logFile.close(); // close the file
}
}
// updateFileName() - Looks through the log files already present on a card,
// and creates a new file with an incremented file index.
void updateFileName()
{
int i = 0;
for (; i < MAX_LOG_FILES; i++)
{
memset(logFileName, 0, strlen(logFileName)); // Clear logFileName string
// Set logFileName to "gpslogXX.csv":
sprintf(logFileName, "%s%d.%s", LOG_FILE_PREFIX, i, LOG_FILE_SUFFIX);
if (!SD.exists(logFileName)) // If a file doesn't exist
{
break; // Break out of this loop. We found our index
}
else // Otherwise:
{
SerialMonitor.print(logFileName);
SerialMonitor.println(" exists"); // Print a debug statement
}
}
SerialMonitor.print("File name: ");
SerialMonitor.println(logFileName); // Debug print the file name
}
void printStats1() {
Wire.beginTransmission(SerLCD_Address);
Wire.write('|'); // Put LCD into setting mode
Wire.write('-'); // Send clear display command
Wire.print("Alt: "); Wire.print(tinyGPS.altitude.feet());
Wire.print(" Course: "); Wire.println(tinyGPS.course.deg());
Wire.print("Speed: "); Wire.println(tinyGPS.speed.mph());
Serial.print("Alt: "); SerialMonitor.println(tinyGPS.altitude.feet());
Serial.print("Course: "); SerialMonitor.println(tinyGPS.course.deg());
Serial.print("Speed: "); SerialMonitor.println(tinyGPS.speed.mph());
}
static void smartDelay(unsigned long ms)
{
unsigned long start = millis();
do
{
// If data has come in from the GPS module
while (gpsPort.available())
tinyGPS.encode(gpsPort.read()); // Send it to the encode function
// tinyGPS.encode(char) continues to "load" the tinGPS object with new
// data coming in from the GPS module. As full NMEA strings begin to come in
// the tinyGPS library will be able to start parsing them for pertinent info
} while (millis() - start < ms);
}
If you are using a passive GPS antenna, you should test it outside (or in an open window pointing the antenna to the sky) to get the satellite fix. TinyGPS lib won't give you back any data if you don't have the fix value

Using SD.remove() and SD library in Arduino

I'm building a program which takes 10 measurements of an analog voltage on pin0 and is printing it to a log file. The issue I'm running into comes when I try to ensure that the file is blank. I am using SD.remove() in order to remove a previous logfile. When I do this, the new log file is never actually written to. When I remove the call to SD.remove(), the program works correctly. Is this some known bug in the SD library or is there some sneaky way around this?
The code is below.
#include <SD.h>
#define OUTPUT_PIN 9 //Using SparkFun MP3 shield
#define DEFAULT_OUTPUT 10
#define VOLTAGE_REF (5)
//Reads a voltage on pin0. by default, the reference voltage is set to 5 V, but
//it can be changed by changing VOLTAGE_REF.
void setup() {
Serial.begin(9600);
Serial.println("Program Initialized");
pinMode(DEFAULT_OUTPUT ,OUTPUT); //Needs to be on to use the library
pinMode(0, INPUT);
if (!SD.begin(OUTPUT_PIN)) {
//init error
Serial.println("Error initializing SD card. Reset the Arduino and try again");
return;
}
Serial.println("Card sucessfully initialized");
if (SD.exists("LOGFILE.LOG") {
SD.remove("LOGFILE.LOG"); //We don't want to use the same file <<THIS IS THE BUG?
}
delay(10); //Make sure changes are applied
File logFile = SD.open("ANALOG.LOG", FILE_WRITE); //Create a new one every time
if (!SD.exists("LOGFILE.LOG")) {
Serial.println("There was some error making a new instance of the logfile?");
delay(1000);
SD.open("ANALOG.LOG", FILE_WRITE);
}
int i;
if (logFile) {
for(i=0;i<10;i++) {
int j = 0;
char str[64];
Serial.print("Reading analog sensor value");
for(j=0;j<=i;j++) {
Serial.print(".");
}
Serial.println();
logFile.print("Read #");
logFile.print(i+1);
logFile.print(" : ");
logFile.print(doVoltageRead(0));
unsigned char l = logFile.println(" V");
if (!l)
Serial.println("No data written");
delay(500);
}
Serial.println("Done.");
logFile.close(); //Close the logfile
Serial.println("Data sucessfully written");
}
else {
//Couldn't create file
Serial.println("There was an error creating the logfile");
}
}
void loop() {
//We don't really need to do anything here
}
float doVoltageRead(int pin) {
int voltageRead = analogRead(pin);
double divisor = (voltageRead * 0.00097752);
float finalVoltage =(VOLTAGE_REF * divisor);
Serial.println(finalVoltage);
return finalVoltage;
}
So.. First you see if LOGFILE.LOG exists, if it does you delete ANALOG.LOG. Then you create ANALOG.LOG. After that you check if LOGFILE.LOG exists. If it doesn't, you print an error and open ANALOG.LOG.
What exactly is the purpose of LOGFILE.LOG? Shouldn't you just change LOGFILE to ANALOG?
I have found the source of the error. When I called if(SD.exists()) after opening a new logfile, the library didn't like that. I am assuming SD.exists() just checks if the address or object returned by open is NULL. However, calling it when the file is already open would cause some strange behaviors. After removing that call inside open, all is well. Thanks for all the suggestions!

Ofstream not writing to file C++

I have this method which supposed to get a buffer and write some content to a file:
void writeTasksToDevice()
{
TaskInfo *task;
unsigned int i = lastTaskWritten;
printf("writing elihsa\n");
outputFile.write(" Elisha2", 7);
//pthread_mutex_lock(&fileMutex);
for(; i < (*writingTasks).size(); i++)
{
task = (*writingTasks).at(i);
if(NULL == task)
{
printf("ERROR!!! in writeTasksToDevice - there's a null task in taskQueue. By "
" design that should NEVER happen\n");
exit(-1);
}
if(true == task->wasItWritten)
{
//continue;
}
else // we've found a task to write!
{
printf("trying to write buffer to file\n");
printf("buffer = %s, length = %d\n", task->buffer, task->length);<====PRINT HERE IS OK< PRINTING WHAT IS WANTED
outputFile.write(task->buffer, task->length); <===SHOULD WRITE HERE
printf("done writing file\n");
}
}
//pthread_mutex_unlock(&fileMutex);
// TODO: check if we should go to sleep and wait for new tasks
// and then go to sleep
}
the buffer content is:
task->buffer: elishaefla
task->length: 10
i opened the stream in another init function using:
outputFile.open(fileName, ios :: app);
if(NULL == outputFile)
{
//print error;
return -1;
}
but at the end, the file content is empty, nothing is being written.
any idea why?
You did not provide enough information to answer the question with certainty, but here are some of the issues you might be facing:
You did not flush the buffer of the ofstream
You did not close the file that you are trying to open later on (if I'm correct, outputFile is a global variable, so it is not closed automatically until the end of the program)