Example #1
0
char * updateFilename(in_file_structPtr in_fp){
    if(in_fp->filename!='\0'){
        free(in_fp->filename);
    }
    in_fp->filename = createFilename(in_fp->basename,in_fp->extension);
    return in_fp->filename;
}
Example #2
0
TimeSliceObservableCDT::TimeSliceObservableCDT(unsigned int writeFrequency, unsigned int T) :
Observable(writeFrequency, 1, false),
filename(createFilename("cdtslice")),
file(filename.c_str()),
T(T),
volumeProfile(T) {

}
Example #3
0
AudioRecord::AudioRecord()
    : sndFormat_(AudioFormat::MONO())
    , filename_(createFilename())
    , savePath_()
    , recorder_(this, Manager::instance().getRingBufferPool())
{
    RING_DBG("Generate filename for this call %s ", filename_.c_str());
}
SpectralDimensionObservable::SpectralDimensionObservable(unsigned int writeFrequency) :
Observable(writeFrequency, 0, true),
sigmaMax(READ_CONF("spec.sigmaMax", 1000)),
diffusionConst(READ_CONF("spec.diff", 1.0)),
dualLattice(READ_CONF("spec.dualLattice", false)),
filename(createFilename("specdim")),
file(filename.c_str()),
specDim(sigmaMax),
specDim1(sigmaMax) {
}
Example #5
0
void AudioRecord::initFilename(const std::string &peerNumber)
{
    RING_DBG("Initialize audio record for peer  : %s", peerNumber.c_str());
    // if savePath_ don't contains filename
    if (savePath_.find(".wav") == std::string::npos) {
        filename_ = createFilename();
        filename_.append("-" + sanitize(peerNumber) + "-" PACKAGE);
        filename_.append(".wav");
    } else {
        filename_ = "";
    }
}
static Bool
JPEGFileToImage (CompDisplay *d,
		 const char  *path,
		 const char  *name,
		 int         *width,
		 int         *height,
		 int         *stride,
		 void        **data)
{
    Bool status = FALSE;
    char *fileName, *extension;

    JPEG_DISPLAY (d);

    fileName = createFilename (path, name);
    if (!fileName)
	return FALSE;

    /* Do some testing here to see if it's got a .jpg or .jpeg extension */
    extension = strrchr (fileName, '.');
    if (extension)
    {
	if (strcasecmp (extension, ".jpeg") == 0 ||
	    strcasecmp (extension, ".jpg") == 0)
	{
	    FILE *file;

	    file = fopen (fileName, "rb");
	    if (file)
	    {
		status = readJPEGFileToImage (file, width, height, data);
		fclose (file);

		if (status)		/* Success! */
		{
		    free (fileName);
    		    *stride = *width * 4;
		    return TRUE;
		}
	    }
	}
    }
    free (fileName);

    /* Isn't a JPEG - pass to the next in the chain. */
    UNWRAP (jd, d, fileToImage);
    status = (*d->fileToImage) (d, path, name, width, height, stride, data);
    WRAP (jd, d, fileToImage, JPEGFileToImage);

    return status;
}
Example #7
0
void K3bVideoDVDRippingDialog::slotUpdateFilenames()
{
  QString baseDir = K3b::prepareDir( m_w->m_editBaseDir->url() );
  d->fsInfo.setPath( baseDir );

  for( QMap<QCheckListItem*, K3bVideoDVDRippingJob::TitleRipInfo>::iterator it = m_titleRipInfos.begin();
       it != m_titleRipInfos.end(); ++it ) {
    QString f = d->fsInfo.fixupPath( createFilename( it.data(), m_w->m_comboFilenamePattern->currentText() ) );
    if( m_w->m_checkBlankReplace->isChecked() )
      f.replace( QRegExp( "\\s" ), m_w->m_editBlankReplace->text() );
    it.data().filename = baseDir + f;
    it.key()->setText( 3, f );
  }
}
Example #8
0
AudioRecord::AudioRecord() : fp (NULL)
    , channels_ (1)
    , byteCounter_ (0)
    , sndSmplRate_ (8000)
    , nbSamplesMic_ (0)
    , nbSamplesSpk_ (0)
    , nbSamplesMax_ (3000)
    , recordingEnabled_ (false)
    , mixBuffer_ (NULL)
    , micBuffer_ (NULL)
    , spkBuffer_ (NULL)
{

    mixBuffer_ = new SFLDataFormat[nbSamplesMax_];
    micBuffer_ = new SFLDataFormat[nbSamplesMax_];
    spkBuffer_ = new SFLDataFormat[nbSamplesMax_];

    createFilename();
}
static Bool
JPEGImageToFile (CompDisplay *d,
		 const char  *path,
		 const char  *name,
		 const char  *format,
		 int         width,
		 int         height,
		 int         stride,
		 void        *data)
{
    Bool status = FALSE;
    char *fileName;
    FILE *file;

    /* Not a JPEG */
    if (strcasecmp (format, "jpeg") != 0 && strcasecmp (format, "jpg") != 0)
    {
	JPEG_DISPLAY (d);
	UNWRAP (jd, d, imageToFile);
	status = (*d->imageToFile) (d, path, name, format,
				    width, height, stride, data);
	WRAP (jd, d, imageToFile, JPEGImageToFile);
	return status;
    }

    /* Is a JPEG */
    fileName = createFilename (path, name);
    if (!fileName)
	return FALSE;

    file = fopen (fileName, "wb");
    if (file)
    {
	status = writeJPEG (d, data, file, width, height, stride);
	fclose (file);
    }

    free (fileName);
    return status;
}
Example #10
0
bool
ReadData::process( SocketPackage& cPackageIn
                 , SocketPackage& cPackageOut )
{
    std::string     sBuffer,
                    sFilename;
    bool            bCanRead    = false;
    std::ifstream   cFile;

    cPackageIn.resetCounter();

    cPackageIn.getString( sBuffer );                // action name
    createFilename( cPackageIn, sFilename, false ); // read two strings

    cFile.open( sFilename.c_str(), std::ios::in|std::ios::binary );
    bCanRead    = cFile.is_open();
    if ( bCanRead )
    {
        struct _stat        nStatus;
        int                 nSize;
        std::vector<char>   caBuffer;

        ::_stat( sFilename.c_str(), &nStatus ); 
        
        nSize   = nStatus.st_size;
        caBuffer.resize( nSize );

        cFile.read( &caBuffer[0], nSize );
        cFile.close();

        cPackageOut.resetCounter();
        cPackageOut.add( &caBuffer[0], nSize );
        cPackageOut.done();
    }
    else
        cPackageOut.resetCounter();

    return bCanRead;
}
Example #11
0
CTCObservable::CTCObservable(unsigned long writeFrequency) :
Observable(writeFrequency, 1, true),
filename(createFilename("ctc")),
file(filename.c_str()) {
}
Example #12
0
int io_writeImage(sParameterStruct * sSO2Parameters, sConfigStruct * config)
{
	FILE *fp;
	short *stBuffer;
	IplImage *img;
	CvMat *png;
	int l;
	int writen_bytes;
	char filename[512];
	int filenamelength = 512;
	int state;
	char *buffer;

	stBuffer = sSO2Parameters->stBuffer;

	/* generate filenames */
	state = createFilename(sSO2Parameters, config, filename, filenamelength, "png");
	if (state) {
		log_error("could not create txt filename");
		return state;
	}
	log_debug("filename created: %s", filename);

	/* convert the image buffer to an openCV image */
	// TODO: check if this has already been done
	// TODO: check return code
	img = bufferToImage(stBuffer);

	/*
	 * encode image as png to buffer
	 * playing with the compression is a huge waste of time with no benefit
	 */
	png = cvEncodeImage(".png", img, 0);

	l = png->rows * png->cols;
	cvReleaseImage(&img);

	// pry the actual buffer pointer from png
	buffer = (char *)malloc(l);
	memcpy(buffer, png->data.s, l);
	cvReleaseMat(&png);

	/* add headers */
	log_debug("insert headers %i", l);
	l = insertHeaders(&buffer, sSO2Parameters, config, l);

	/* save image to disk */
	log_debug("open new png file %i", l);
	fp = fopen(filename, "wb");
	if (fp) {
		writen_bytes = fwrite(buffer, 1, l, fp);
		state = writen_bytes == l ? 0 : 1;
		if (state) {
			log_error("PNG image wasn't written correctly");
		}
		fclose(fp);
	} else {
		state = 1;
		log_error("Couldn't open png file");
	}

	/* cleanup */
	free(buffer);

	if (!state) {
		log_message("png image written");
	}

	return state;
}
Example #13
0
/*!
 * \brief Remove temporary directory.
 * \param basePath [in] Path of temporary directory.
 */
void removeTempDir(char const *basePath) {
  /* If failure open directory. */
  if (unlikely(basePath == NULL)) {
    logger->printWarnMsg("Illegal directory path.");
    return;
  }

  /* Open directory. */
  DIR *dir = opendir(basePath);

  /* If failure open directory. */
  if (unlikely(dir == NULL)) {
    logger->printWarnMsgWithErrno("Couldn't open directory.");
    return;
  }

  /* Store error number. */
  int oldErrNum = errno;
  /* Read file in directory. */
  struct dirent *entry = NULL;
  while ((entry = readdir(dir)) != NULL) {
    /* Check file name. */
    if (strcmp(entry->d_name, "..") == 0 || strcmp(entry->d_name, ".") == 0) {
      continue;
    }

    /* Get remove file's full path. */
    char *removePath = createFilename(basePath, entry->d_name);

    /* All file need remove. */
    if (unlikely(removePath == NULL || unlink(removePath) != 0)) {
      /* Skip file remove. */
      if (removePath == NULL) {
        errno = ENOMEM;  // This error may be caused by ENOMEM because malloc()
                         // failed.
      }
      char *printPath = (removePath != NULL) ? removePath : entry->d_name;
      logger->printWarnMsgWithErrno("Failure remove file. path: \"%s\"",
                                    printPath);
    }

    /* Cleanup. */
    free(removePath);
    oldErrNum = errno;
  }

  /* If failure in read directory. */
  if (unlikely(errno != oldErrNum)) {
    logger->printWarnMsgWithErrno("Failure search file in directory.");
  }

  /* Cleanup. */
  closedir(dir);

  /* Get mutex. */
  ENTER_PTHREAD_SECTION(&directoryMutex) {

    /* Remove directory. */
    if (unlikely(rmdir(basePath) != 0)) {
      /* Skip directory remove. */
      logger->printWarnMsgWithErrno("Failure remove directory.");
    }

  }
  /* Release mutex. */
  EXIT_PTHREAD_SECTION(&directoryMutex)
}
/**
 * Dive into a folder and recurse depth-first to perform a pre-set operation lsAction:
 *   LS_Count       - Add +1 to nrFiles for every file within the parent
 *   LS_GetFilename - Get the filename of the file indexed by nrFiles
 *   LS_SerialPrint - Print the full path of each file to serial output
 */
void CardReader::lsDive(const char *prepend, SdFile parent, const char * const match/*=NULL*/) {
  dir_t p;
  uint8_t cnt = 0;

  // Read the next entry from a directory
  while (parent.readDir(p, longFilename) > 0) {

    // If the entry is a directory and the action is LS_SerialPrint
    if (DIR_IS_SUBDIR(&p) && lsAction != LS_Count && lsAction != LS_GetFilename) {

      // Get the short name for the item, which we know is a folder
      char lfilename[FILENAME_LENGTH];
      createFilename(lfilename, p);

      // Allocate enough stack space for the full path to a folder, trailing slash, and nul
      boolean prepend_is_empty = (prepend[0] == '\0');
      int len = (prepend_is_empty ? 1 : strlen(prepend)) + strlen(lfilename) + 1 + 1;
      char path[len];

      // Append the FOLDERNAME12/ to the passed string.
      // It contains the full path to the "parent" argument.
      // We now have the full path to the item in this folder.
      strcpy(path, prepend_is_empty ? "/" : prepend); // root slash if prepend is empty
      strcat(path, lfilename); // FILENAME_LENGTH-1 characters maximum
      strcat(path, "/");       // 1 character

      // Serial.print(path);

      // Get a new directory object using the full path
      // and dive recursively into it.
      SdFile dir;
      if (!dir.open(parent, lfilename, O_READ)) {
        if (lsAction == LS_SerialPrint) {
          ECHO_LMV(ER, MSG_SD_CANT_OPEN_SUBDIR, lfilename);
        }
      }
      lsDive(path, dir);
      // close() is done automatically by destructor of SdFile
    }
    else {
      char pn0 = p.name[0];
      if (pn0 == DIR_NAME_FREE) break;
      if (pn0 == DIR_NAME_DELETED || pn0 == '.') continue;
      if (longFilename[0] == '.') continue;

      if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;

      filenameIsDir = DIR_IS_SUBDIR(&p);

      if (!filenameIsDir && (p.name[8] != 'G' || p.name[9] == '~')) continue;

      switch (lsAction) {
        case LS_Count:
          nrFiles++;
          break;
        case LS_SerialPrint:
          createFilename(filename, p);
          ECHO_V(prepend);
          ECHO_EV(filename);
          break;
        case LS_GetFilename:
          createFilename(filename, p);
          if (match != NULL) {
            if (strcasecmp(match, filename) == 0) return;
          }
          else if (cnt == nrFiles) return;
          cnt++;
          break;
      }
    }
  } // while readDir
}
Example #15
0
/*!
 * \brief Copy data as avoid overwriting.
 * \param sourceFile [in] Path of source file.
 * \param destPath   [in] Path of directory put duplicated file.
 * \param destName   [in] Name of duplicated file.<br>
 *                        Don't rename, if value is null.
 * \return Value is zero, if process is succeed.<br />
 *         Value is error number a.k.a. "errno", if process is failure.
 */
int copyFile(char const *sourceFile, char const *destPath,
             char const *destName) {
  char rpath[PATH_MAX];

  if (unlikely(!isCopiablePath(sourceFile, rpath))) {
    return EINVAL;
  }

  int result = 0;
  /* Make file name. */
  char *newFile = destName == NULL
                      ? createFilename(destPath, (char *)sourceFile)
                      : createFilename(destPath, (char *)destName);

  /* Failure make filename. */
  if (unlikely(newFile == NULL)) {
    logger->printWarnMsg("Couldn't allocate copy source file path.");

    /*
     * Because exist below two pattern when "createFilename" return NULL.
     * 1, Illegal argument. "errno" don't change.
     * 2, No usable memory. "errno" maybe "ENOMEM".
     */
    return (errno != 0) ? errno : EINVAL;
  }

  /* Get uniq file name. */
  char *destFile = createUniquePath(newFile, false);
  if (unlikely(destFile == NULL)) {
    logger->printWarnMsg("Couldn't allocate unique destination file name.");
    free(newFile);
    return ENOMEM;
  }

  /* Open copy source file. */
  int sourceFd = open(sourceFile, O_RDONLY);
  if (unlikely(sourceFd < 0)) {
    result = errno;
    logger->printWarnMsgWithErrno("Couldn't open copy source file.");
    free(newFile);
    free(destFile);
    return result;
  }

  /* Get source file size */
  struct stat st;
  if (unlikely(fstat(sourceFd, &st) != 0)) {
    result = errno;
    logger->printWarnMsgWithErrno("Couldn't open copy destination file.");
    free(newFile);
    free(destFile);
    close(sourceFd);
    return result;
  }

  /* Open destination file. */
  int destFd = open(destFile, O_CREAT | O_EXCL | O_WRONLY, S_IRUSR | S_IWUSR);
  if (unlikely(destFd < 0)) {
    result = errno;
    logger->printWarnMsgWithErrno("Couldn't open copy destination file.");
    free(newFile);
    free(destFile);
    close(sourceFd);
    return result;
  }

  /* Copy data */
  if (st.st_size > 0) {
    if (unlikely(sendfile64(destFd, sourceFd, NULL, st.st_size) == -1)) {
      result = errno;
      logger->printWarnMsgWithErrno("Couldn't copy file.");
    }
  } else { /* This route is for files in procfs */
    char buf[1024];
    ssize_t read_size;

    while ((read_size = read(sourceFd, buf, 1024)) > 0) {
      if (write(destFd, buf, (size_t)read_size) == -1) {
        read_size = -1;
        break;
      }
    }

    if (read_size == -1) {
      result = errno;
      logger->printWarnMsgWithErrno("Couldn't copy file.");
    }
  }

  /* Clean up */
  close(sourceFd);

  if (unlikely((close(destFd) != 0) && (result == 0))) {
    result = errno;
    logger->printWarnMsgWithErrno("Couldn't write copy file data.");
  }

  free(newFile);
  free(destFile);

  return result;
}
Example #16
0
void  CardReader::lsDive(const char *prepend,SdFile parent)
{
    dir_t p;
    uint8_t cnt=0;

    while (parent.readDir(p, longFilename) > 0)
    {
        if( DIR_IS_SUBDIR(&p) && lsAction!=LS_Count && lsAction!=LS_GetFilename) // hence LS_SerialPrint
        {

            char path[13*2];
            char lfilename[13];
            createFilename(lfilename,p);

            path[0]=0;
            if(strlen(prepend)==0) //avoid leading / if already in prepend
            {
                strcat(path,"/");
            }
            strcat(path,prepend);
            strcat(path,lfilename);
            strcat(path,"/");

            //Serial.print(path);

            SdFile dir;
            if(!dir.open(parent,lfilename, O_READ))
            {
                if(lsAction==LS_SerialPrint)
                {
                    SERIAL_ECHO_START;
                    SERIAL_ECHOLN(MSG_SD_CANT_OPEN_SUBDIR);
                    SERIAL_ECHOLN(lfilename);
                }
            }
            lsDive(path,dir);
            //close done automatically by destructor of SdFile


        }
        else
        {
            if (p.name[0] == DIR_NAME_FREE) break;
            if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.'|| p.name[0] == '_') continue;
            if ( p.name[0] == '.')
            {
                if ( p.name[1] != '.')
                    continue;
            }

            if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;
            filenameIsDir=DIR_IS_SUBDIR(&p);


            if(!filenameIsDir)
            {
                if(p.name[8]!='G') continue;
                if(p.name[9]=='~') continue;
            }
            //if(cnt++!=nr) continue;
            createFilename(filename,p);
            if(lsAction==LS_SerialPrint)
            {
                SERIAL_PROTOCOL(prepend);
                SERIAL_PROTOCOLLN(filename);
            }
            else if(lsAction==LS_Count)
            {
                nrFiles++;
            }
            else if(lsAction==LS_GetFilename)
            {
                if(cnt==nrFiles)
                    return;
                cnt++;

            }
        }
    }
}
Example #17
0
int io_writeDump(sParameterStruct * sSO2Parameters, sConfigStruct * config)
{
	FILE *imageFile;
	FILE *fp;
	char headerfile[512];
	int headerfilelength = 512;
	char rawfile[512];
	int rawfilelength = 512;
	int fwriteReturn;
	int state = 0;
	char iso_date[25];

	/* generate filenames */
	state = createFilename(sSO2Parameters, config, headerfile, headerfilelength, "txt");
	if(state){
		log_error("could not create txt filename");
	}

	state = createFilename(sSO2Parameters, config, rawfile, rawfilelength, "raw");
	if (state) {
		log_error("could not create txt filename");
	}

	/* Open a new file for the image (writeable, binary) */
	imageFile = fopen(rawfile, "wb");
	if (imageFile != NULL) {
		fwriteReturn = fwrite(sSO2Parameters->stBuffer, 1, config->dBufferlength * 2, imageFile);
		if(fwriteReturn != config->dBufferlength * 2){
			log_debug("could not write raw file %i != %i", config->dBufferlength, fwriteReturn);
			log_error("could not write raw file");
		}
		fclose(imageFile);
	} else {
		log_error("not opened raw file");
	}

	/* write a text file containing header information */
	fp = fopen(headerfile, "ab");
	if (fp != NULL) {
		fprintf(fp, "dBufferlength %i\n", config->dBufferlength);
		fprintf(fp, "dHistMinInterval %i\n", config->dHistMinInterval);
		fprintf(fp, "dHistPercentage %i\n", config->dHistPercentage);
		fprintf(fp, "dDarkCurrent %i\n", (int)sSO2Parameters->dDarkCurrent);
		fprintf(fp, "dImageCounter %i\n", (int)config->dImageCounter);
		fprintf(fp, "dInterFrameDelay %i\n", (int)config->dInterFrameDelay);
		fprintf(fp, "dTriggerPulseWidth %i\n", (int)sSO2Parameters->dTriggerPulseWidth);
		fprintf(fp, "dExposureTime %f\n", sSO2Parameters->dExposureTime);
		fprintf(fp, "cConfigFileName %s\n", config->cConfigFileName);
		fprintf(fp, "cFileNamePrefix %s\n", config->cFileNamePrefix);
		fprintf(fp, "cImagePath %s\n", config->cImagePath);
		fprintf(fp, "dFixTime %i\n", config->dFixTime);
		dateStructToISO8601(sSO2Parameters->timestampBefore, iso_date);
		fprintf(fp, "timestampBefore %s\n", iso_date);

		fclose(fp);
	} else {
		log_error("not opened text file");
	}

	log_message("dumb image written");

	return 0;
}