本文整理汇总了C++中FILE类的典型用法代码示例。如果您正苦于以下问题:C++ FILE类的具体用法?C++ FILE怎么用?C++ FILE使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FILE类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
int main(int argc, char** argv)
{
double d;
int n = 1;
if( argc!=2) {
printf( "usage: program <number of numbers to read>\n");
return -1;
}
#ifdef STDIO
FILE *f;
f = fopen( "numbers.txt", "r");
if ( !f) {
printf( "Cannot open file\n");
return -1;
}
VALUES = atoi( argv[1]);
for ( ; VALUES; --VALUES) {
fscanf( f,"%lf", &d);
printf( "%10.5f", d);
#else
ifstream f( "numbers.txt", ios_base::in);
if( !f.is_open()) {
cout << "Cannot open file\n";
return -1;
}
VALUES = atoi( argv[1]);
for ( ; VALUES; --VALUES) {
f >> d;
cout << std::setw(10)
<< std::setprecision(5)
<< std::setiosflags( ios::showpoint)
<< std::setiosflags( ios::fixed)
<< d;
#endif
if (n % 5 == 0) {
#ifdef STDIO
printf("\n");
#else
cout << '\n';
#endif
}
}
#ifdef STDIO
fclose( f);
#else
f.close();
#endif
return (EXIT_SUCCESS);
}
示例2: lseek
off_t lseek(int fid, off_t offset, int whence)
{
off_t rc;
FILE *file;
#if OS_PARM_CHECK
/*-------------------------------------------------------------------*/
/* If the file descriptor is invalid, return error. */
/*-------------------------------------------------------------------*/
if (fid < 0 || fid >= FOPEN_MAX)
{
set_errno(EBADF);
return -1;
}
if (Files[fid].flags & FCB_DIR)
{
set_errno(EISDIR);
return -1;
}
#endif
/*-------------------------------------------------------------------*/
/* Get exclusive access to upper file system. */
/*-------------------------------------------------------------------*/
semPend(FileSysSem, WAIT_FOREVER);
/*-------------------------------------------------------------------*/
/* Return error if file is closed. */
/*-------------------------------------------------------------------*/
file = &Files[fid];
if (file->ioctl == NULL)
{
set_errno(EBADF);
semPost(FileSysSem);
return -1;
}
/*-------------------------------------------------------------------*/
/* Acquire exclusive access to lower file system. */
/*-------------------------------------------------------------------*/
file->acquire(file, F_READ | F_WRITE);
/*-------------------------------------------------------------------*/
/* Call file system specific FSEEK routine. */
/*-------------------------------------------------------------------*/
rc = (off_t)file->ioctl(file, FSEEK, (long)offset, whence);
/*-------------------------------------------------------------------*/
/* Release exclusive access to file systems and return result. */
/*-------------------------------------------------------------------*/
file->release(file, F_READ | F_WRITE);
semPost(FileSysSem);
return rc;
}
示例3: stackToFile
bool stackToFile(const Common::String &filename, const Variable &from) {
#if 0
FILE *fp = fopen(filename, saveEncoding ? "wb" : "wt");
if (!fp) return fatal("Can't create file", filename);
VariableStack *hereWeAre = from.varData.theStack -> first;
encode1 = (byte)saveEncoding & 255;
encode2 = (byte)(saveEncoding >> 8);
if (saveEncoding) {
fprintf(fp, "[Custom data (encoded)]\r\n");
writeStringEncoded(UTF8_CHECKER, fp);
} else {
fprintf(fp, "[Custom data (ASCII)]\n");
}
while (hereWeAre) {
if (saveEncoding) {
switch (hereWeAre -> thisVar.varType) {
case SVT_STRING:
fputc(encode1, fp);
writeStringEncoded(hereWeAre -> thisVar.varData.theString, fp);
break;
case SVT_INT:
// Small enough to be stored as a char
if (hereWeAre -> thisVar.varData.intValue >= 0 && hereWeAre -> thisVar.varData.intValue < 256) {
fputc(2 ^ encode1, fp);
fputc(hereWeAre -> thisVar.varData.intValue, fp);
} else {
fputc(1 ^ encode1, fp);
fp->writeUint32LE(hereWeAre -> thisVar.varData.intValue);
}
break;
default:
fatal("Can't create an encoded custom data file containing anything other than numbers and strings", filename);
fclose(fp);
return false;
}
} else {
char *makeSureItsText = getTextFromAnyVar(hereWeAre -> thisVar);
if (makeSureItsText == NULL) break;
fprintf(fp, "%s\n", makeSureItsText);
delete makeSureItsText;
}
hereWeAre = hereWeAre -> next;
}
fclose(fp);
#endif
return true;
}
示例4: canonizePath
// ctor: input is filename to open.
// only std::ios::in is supported currently.
// if _makeGlobal == TRUE, then the ZipFile is added to the list
// of global zip files.
zppZipArchive::zppZipArchive(const std::string &_fn, std::ios::openmode _mode, bool _makeGlobal)
{
ourFile = false;
zipName = _fn;
canonizePath(zipName);
#ifdef ZPP_INCLUDE_CRYPT
passwd = NULL;
#endif
if (_mode & std::ios_base::in) {
// make sure "binary" mode is selected.
_mode |= std::ios_base::binary;
#ifdef ZPP_USE_STDIO
FILE *infile = fopen(zipName.c_str(),"rb");
current_pos_v=0;
#else
std::ifstream *infile = new std::ifstream();
infile->open(zipName.c_str(),_mode);
#endif
ourFile = true;
#ifdef ZPP_USE_STDIO
if (!infile)
throw zppError("can't open zip file");
#else
if (infile->fail())
throw zppError("can't open zip file");
#endif
str = infile;
} else {
throw ("zppZipArchive:: only std::ios::in currently supported.");
}
priority = defaultPriority;
isGlobal = _makeGlobal;
// build internal data structures
parseZipDirectory();
}
示例5: fcntl
int fcntl(int fid, int cmd, ...)
{
va_list ap;
FILE *file;
#if OS_PARM_CHECK
/*-------------------------------------------------------------------*/
/* If the file descriptor is invalid, return error. */
/*-------------------------------------------------------------------*/
if (fid < 0 || fid >= FOPEN_MAX)
{
set_errno(EBADF);
return -1;
}
#endif
/*-------------------------------------------------------------------*/
/* Get exclusive access to upper file system. */
/*-------------------------------------------------------------------*/
semPend(FileSysSem, WAIT_FOREVER);
/*-------------------------------------------------------------------*/
/* Return error if file is closed. */
/*-------------------------------------------------------------------*/
file = &Files[fid];
if (file->ioctl == NULL)
{
semPost(FileSysSem);
set_errno(EBADF);
return -1;
}
/*-------------------------------------------------------------------*/
/* Based on the command, execute the right instructions. */
/*-------------------------------------------------------------------*/
switch (cmd)
{
case F_DUPFD:
{
/*---------------------------------------------------------------*/
/* Use the va_arg mechanism to get the argument. */
/*---------------------------------------------------------------*/
va_start(ap, cmd);
fid = va_arg(ap, int);
va_end(ap);
#if OS_PARM_CHECK
/*---------------------------------------------------------------*/
/* If the file descriptor is invalid, return error. */
/*---------------------------------------------------------------*/
if (fid < 0 || fid >= FOPEN_MAX)
{
semPost(FileSysSem);
set_errno(EINVAL);
return -1;
}
#endif
/*---------------------------------------------------------------*/
/* Look for free file control block identifier >= fid. */
/*---------------------------------------------------------------*/
for (;;)
{
FILE *file2 = &Files[fid];
/*-------------------------------------------------------------*/
/* Check if file control block is free. */
/*-------------------------------------------------------------*/
if (file2->ioctl == NULL)
{
/*-----------------------------------------------------------*/
/* Copy previous file control block to new one. */
/*-----------------------------------------------------------*/
*file2 = *file;
/*-----------------------------------------------------------*/
/* Acquire exclusive access to lower file system. */
/*-----------------------------------------------------------*/
file2->acquire(file2, F_READ | F_WRITE);
/*-----------------------------------------------------------*/
/* Call file system specific DUP routine. */
/*-----------------------------------------------------------*/
file2->ioctl(file2, DUP);
/*-----------------------------------------------------------*/
/* Release exclusive access to lower file system. */
/*-----------------------------------------------------------*/
file2->release(file2, F_READ | F_WRITE);
break;
}
/*-------------------------------------------------------------*/
/* If none are free, set errno and break. */
/*-------------------------------------------------------------*/
if (++fid >= FOPEN_MAX)
{
set_errno(EMFILE);
fid = -1;
break;
}
//.........这里部分代码省略.........
示例6: parseObjFile
void parseObjFile(const char* objPath,
std::vector<glm::vec3>& vertices, std::vector<glm::vec2>& texcoords,
std::vector<glm::vec3>& normals, std::vector<GLuint>& vertIndices,
std::vector<GLuint>& texIndices, std::vector<GLuint>& normIndices) {
#if (defined USE_FSCANF || defined USE_FGETS)
GLchar buf[BUFSIZE];
FILE* fp;
// in Win/VS2010, position from ftell after fopen in text mode
// is not accurate (due to translation of newlines)
if ((NULL == objPath) || (NULL == (fp = fopen(objPath, "rb")))) {
return;
}
#ifdef USE_FSCANF
while (EOF != fscanf(fp, "%s", buf)) {
#else // USE_FGETS
while (NULL != fgets(buf, sizeof(buf), fp)) {
#endif
#else // USE_GETLINE
GLchar* buf;
std::string str;
std::ifstream fp(objPath);
if (!fp.is_open()) {
return;
}
while (fp.good()) {
std::getline(fp, str);
#endif
GLint res = 0;
#ifdef USE_GETLINE
buf = (GLchar*)str.c_str();
#endif
switch (buf[0]) {
case 'v':
#if (defined USE_FGETS || defined USE_GETLINE)
if (' ' == buf[1]) {
#else // USE_FSCANF
if (1 == strlen(buf)) {
#endif
glm::vec3 vert;
#if (defined USE_FGETS || defined USE_GETLINE)
res = sscanf(buf, "v %f %f %f",
#else // USE_FSCANF
res = fscanf(fp, "%f %f %f\n",
#endif
&vert.x, &vert.y, &vert.z);
if (DIM3 != res) {
fprintf(stderr, "Incorrect vert matches on sscanf\n");
}
vertices.push_back(vert);
} else if ('t' == buf[1]) {
glm::vec2 tex;
#if (defined USE_FGETS || defined USE_GETLINE)
res = sscanf(buf, "vt %f %f",
#else // USE_FSCANF
res = fscanf(fp, "%f %f\n",
#endif
&tex.x, &tex.y);
if (DIM2 != res) {
fprintf(stderr, "Incorrect tex matches on sscanf\n");
}
texcoords.push_back(tex);
} else if ('n' == buf[1]) {
glm::vec3 norm;
#if (defined USE_FGETS || defined USE_GETLINE)
res = sscanf(buf, "vn %f %f %f",
#else // USE_FSCANF
res = fscanf(fp, "%f %f %f\n",
#endif
&norm.x, &norm.y, &norm.z);
if (DIM3 != res) {
fprintf(stderr, "Incorrect norm matches on sscanf\n");
}
normals.push_back(norm);
}
break;
case 'f':
GLuint vertsIdx[VERTS_FACE], normsIdx[VERTS_FACE],
texIdx[VERTS_FACE] = { 1, 1, 1 };
#if (defined USE_FGETS || defined USE_GETLINE)
res = sscanf(buf, "f %d/%d/%d %d/%d/%d %d/%d/%d",
#else // USE_FSCANF
// ensure fopen with binary NOT text mode for Win/VS2010
long posPtr = ftell(fp); // get current stream pos
res = fscanf(fp, "%d/%d/%d %d/%d/%d %d/%d/%d\n",
#endif
&vertsIdx[0], &texIdx[0], &normsIdx[0],
&vertsIdx[1], &texIdx[1], &normsIdx[1],
&vertsIdx[2], &texIdx[2], &normsIdx[2]);
if (RES_VertTexNorm != res) {
#if (defined USE_FGETS || defined USE_GETLINE)
res = sscanf(buf, "f %d//%d %d//%d %d//%d",
#else // USE_FSCANF
fseek(fp, posPtr, SEEK_SET); // reset stream pos
res = fscanf(fp, "%d//%d %d//%d %d//%d\n",
#endif
//.........这里部分代码省略.........
示例7: do_import
int
do_import(std::string file, int sorted, uint_t limit,
int &rnadded, int &rnlines) {
#if defined USE_CXX_IO
std::ifstream fin(file.c_str());
#else
FILE *fin = fopen(file.c_str(), "r");
#endif
int fd = open(file.c_str(), O_RDONLY);
// Potential race condition + not checking for return value
if_length = file_size(file.c_str());
DCERR("handle_import::file:"<<file<<endl);
if (!fin || !fd) {
return -IMPORT_FILE_NOT_FOUND;
}
else {
building = true;
int nlines = 0;
int foffset = 0;
if (if_mmap_addr) {
munmap(if_mmap_addr, if_length);
}
// mmap() the input file in
if_mmap_addr = (char*)mmap(NULL, if_length, PROT_READ, MAP_SHARED, fd, 0);
if (!if_mmap_addr) {
fclose(fin);
close(fd);
return -IMPORT_FILE_NOT_FOUND;
}
pm.repr.clear();
char buff[INPUT_LINE_SIZE];
while (
#if defined USE_CXX_IO
fin
#else
!feof(fin)
#endif
&& limit--) {
buff[0] = '\0';
#if defined USE_CXX_IO
fin.getline(buff, INPUT_LINE_SIZE);
const int llen = fin.gcount();
buff[INPUT_LINE_SIZE - 1] = '\0';
#else
char *got = fgets(buff, INPUT_LINE_SIZE, fin);
if (!got) {
break;
}
const int llen = strlen(buff);
if (llen && buff[llen-1] == '\n') {
buff[llen-1] = '\0';
}
#endif
++nlines;
int weight = 0;
std::string phrase;
StringProxy snippet;
InputLineParser(if_mmap_addr, foffset, buff, &weight, &phrase, &snippet).start_parsing();
foffset += llen;
if (!phrase.empty()) {
str_lowercase(phrase);
DCERR("Adding: "<<weight<<", "<<phrase<<", "<<std::string(snippet)<<endl);
pm.insert(weight, phrase, snippet);
}
}
fclose(fin);
pm.finalize(sorted);
vui_t weights;
for (size_t i = 0; i < pm.repr.size(); ++i) {
weights.push_back(pm.repr[i].weight);
}
st.initialize(weights);
rnadded = weights.size();
rnlines = nlines;
building = false;
}
return 0;
}
示例8: processCCO
void
processCCO(SnapConConMesg *cco) {
int *contigGapToUngap = NULL;
int contigLengthGapped = strlen(cco->consensus);
int contigLengthUngap = 0;
int i = 0, j = 0;
int isDegenerate = 0;
// By definition, a degenerate contig has one unitig and is unplaced.
// In reality, those two conditions always occur together.
//
FILE *len = ctglen;
FILE *frg = frgctg;
FILE *utg = utgctg;
FILE *var = varctg;
if ((cco->placed == AS_UNPLACED) && (cco->num_unitigs == 1)) {
isDegenerate = 1;
len = deglen;
frg = frgdeg;
utg = utgdeg;
var = vardeg;
}
contigGapToUngap = (int *)safe_calloc(contigLengthGapped + 1, sizeof(int));
contigGapToUngap[0] = 0;
for (i=0; i<contigLengthGapped; i++) {
if (cco->consensus[i] != '-')
contigLengthUngap++;
contigGapToUngap[i+1] = contigLengthUngap;
}
fprintf(len, "%s\t%d\n",
AS_UID_toString(cco->eaccession),
contigLengthUngap);
if (isDegenerate == 0)
fprintf(ctginf, "%s\t%d\t%d\t%d\t%d\n",
AS_UID_toString(cco->eaccession),
contigLengthUngap,
cco->num_unitigs,
cco->num_pieces,
cco->num_vars);
else
fprintf(deginf, "%s\t%d\t%d\t%d\t%d\t%s\t%f\t%f\n",
AS_UID_toString(cco->eaccession),
contigLengthUngap,
cco->num_unitigs,
cco->num_pieces,
cco->num_vars,
AS_UID_toString(cco->unitigs[0].eident),
covStat[cco->unitigs[0].eident],
microHet[cco->unitigs[0].eident]);
uid2iid[cco->eaccession] = cco->iaccession;
if (ctgInfoMax <= cco->iaccession) {
ctgInfoMax *= 2;
ctgInfo = (ctgInfo_t *)safe_realloc(ctgInfo, ctgInfoMax * sizeof(ctgInfo_t));
}
ctgInfo[cco->iaccession].len = contigLengthUngap;
// VAR/variants
for (i=0; i<cco->num_vars; i++) {
IntMultiVar *v = cco->vars + i;
int bgn = contigGapToUngap[v->position.bgn];
int end = contigGapToUngap[v->position.end];
fprintf(var, "%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%s\t%s\t%s\n",
v->enc_var_seq,
AS_UID_toString(cco->eaccession),
bgn, end,
v->num_reads,
v->num_alleles_confirmed,
v->min_anchor_size,
v->var_length,
v->enc_num_reads,
v->enc_weights,
v->enc_read_ids);
}
// Remember what fragments were placed. This is used to ignore
// some fragments when reporting unplaced surrogate fragments.
set<AS_UID> placed;
// MPS/fragments
for (i=0; i<cco->num_pieces; i++) {
int bgn = contigGapToUngap[cco->pieces[i].position.bgn];
int end = contigGapToUngap[cco->pieces[i].position.end];
char ori = ORIF;
// If bgn == end, then the fragment fell entirely within a gap.
if (cco->pieces[i].position.bgn > cco->pieces[i].position.end) {
ori = ORIR;
//.........这里部分代码省略.........
示例9: creatn
int creatn(const char *path, mode_t mode, size_t size)
{
int rv = -1;
void *dir;
FILE *file;
#if !_PATH_NO_TRUNC
char trunc_path[PATH_MAX + 1];
#endif
#if OS_PARM_CHECK
/*-------------------------------------------------------------------*/
/* If path is NULL, return -1. */
/*-------------------------------------------------------------------*/
if (path == NULL)
{
set_errno(EFAULT);
return -1;
}
#endif
/*-------------------------------------------------------------------*/
/* Acquire exclusive access to upper file system. */
/*-------------------------------------------------------------------*/
semPend(FileSysSem, WAIT_FOREVER);
/*-------------------------------------------------------------------*/
/* Find a free file control block and initialize it. */
/*-------------------------------------------------------------------*/
for (file = &Files[0]; file->ioctl; ++file)
{
/*-----------------------------------------------------------------*/
/* If none are free, return error. */
/*-----------------------------------------------------------------*/
if (file == &Files[FOPEN_MAX - 1])
{
set_errno(EMFILE);
semPost(FileSysSem);
return -1;
}
}
FsInitFCB(file, FCB_FILE);
/*-------------------------------------------------------------------*/
/* Ensure path is valid. */
/*-------------------------------------------------------------------*/
dir = FSearch(file, &path, PARENT_DIR);
if (dir == NULL)
goto end;
/*-------------------------------------------------------------------*/
/* If path too long, return error if no truncation, else truncate. */
/*-------------------------------------------------------------------*/
if (strlen(path) > PATH_MAX)
{
#if _PATH_NO_TRUNC
set_errno(ENAMETOOLONG);
goto end;
#else
strncpy(trunc_path, path, PATH_MAX);
trunc_path[PATH_MAX] = '\0';
path = trunc_path;
#endif
}
/*-------------------------------------------------------------------*/
/* Acquire exclusive access to lower file system. */
/*-------------------------------------------------------------------*/
file->acquire(file, F_READ | F_WRITE);
/*-------------------------------------------------------------------*/
/* Call file system specific CREATN routine. */
/*-------------------------------------------------------------------*/
rv = (int)file->ioctl(file, CREATN, path, mode, size, dir);
/*-------------------------------------------------------------------*/
/* Release exclusive access to lower file system. */
/*-------------------------------------------------------------------*/
file->release(file, F_READ | F_WRITE);
/*-------------------------------------------------------------------*/
/* Free control block if error, else set return value. */
/*-------------------------------------------------------------------*/
end:
if (rv == -1)
file->ioctl = NULL;
else
rv = file - &Files[0];
/*-------------------------------------------------------------------*/
/* Release exclusive access to upper file system and return result. */
/*-------------------------------------------------------------------*/
semPost(FileSysSem);
return rv;
}
示例10: time
void VmBase::refresh_most()
{
vm_ids_.clear();
stable_vmthread_id_to_vm_id_.clear();
name_.clear();
uuid_.clear();
vsocket_num_.clear();
vcore_num_.clear();
vhpthread_num_.clear();
total_mem_size_.clear();
string cmd = "ps -C " + vm_cmd_ + " -wwo etime=,pid=,args=";
time_t cur_time;
time(&cur_time);
FILE* data = popen(cmd.c_str(), "r");
string pid;
string start_timestamp;
vector<string> args;
string tmp_str;
while(fgets(buf_.get(), BUF_SIZE, data))
{
args.clear();
istringstream is(buf_.get());
is >> start_timestamp;
long long days = 0;
long long hours = 0;
long long minutes = 0;
long long seconds = 0;
time_t start_time;
if (count(start_timestamp.begin(), start_timestamp.end(), '-') > 0)
sscanf(start_timestamp.c_str(), "%lld-%lld:%lld:%lld", &days, &hours, &minutes, &seconds);
else if (count(start_timestamp.begin(), start_timestamp.end(), ':') == 2)
sscanf(start_timestamp.c_str(), "%lld:%lld:%lld", &hours, &minutes, &seconds);
else if (count(start_timestamp.begin(), start_timestamp.end(), ':') == 1)
sscanf(start_timestamp.c_str(), "%lld:%lld", &minutes, &seconds);
start_time = cur_time - (((days * 24 + hours) * 60 + minutes) * 60 + seconds);
is >> pid;
while(is)
{
is >> tmp_str;
args.push_back(tmp_str);
}
//add vm_ids
VmId vm_id(start_time, stoull(pid));
vm_ids_.insert(vm_id);
//add name
string name = "";
auto name_iter = find(args.begin(), args.end(), "-name");
if (name_iter != args.end())
{
++name_iter;
name = *name_iter;
}
else
{
//TODO throw //because of cgroup need it
}
name_[vm_id] = name;
//add uuid
string uuid = "";
auto uuid_iter = find(args.begin(), args.end(), "-uuid");
if (uuid_iter != args.end())
{
++uuid_iter;
uuid = *uuid_iter;
}
uuid_[vm_id] = uuid;
//add vsocket vcore vhpthread
auto iter = find(args.begin(), args.end(), "-smp");
if (iter != args.end())
{
++iter;
vector<string> ops;
str_tools::split(*iter, ',', ops);
for(auto& op : ops)
{
vector<string> data;
str_tools::split(op, '=', data);
if (data.size() == 2) {
if(data[0] == "sockets")
vsocket_num_[vm_id] = stoi(data[1]);
else if(data[0] == "cores")
vcore_num_[vm_id] = stoi(data[1]);
else if(data[0] == "threads")
vhpthread_num_[vm_id] = stoi(data[1]);
}
}
}
//add total_mem_size
int size = -1;
auto size_iter = find(args.begin(), args.end(), "-m");
if (size_iter != args.end())
//.........这里部分代码省略.........
示例11: write
int write(int fid, const void *buf, unsigned int nbytes)
{
int written;
FILE *file;
#if OS_PARM_CHECK
/*-------------------------------------------------------------------*/
/* Ensure file descriptor is valid. */
/*-------------------------------------------------------------------*/
if (fid < 0 || fid >= FOPEN_MAX)
{
set_errno(EBADF);
return -1;
}
/*-------------------------------------------------------------------*/
/* Return error if buffer pointer is invalid. */
/*-------------------------------------------------------------------*/
if (buf == NULL)
{
Files[fid].errcode = EFAULT;
set_errno(EFAULT);
return -1;
}
#endif
/*-------------------------------------------------------------------*/
/* Acquire exclusive write access to stream. */
/*-------------------------------------------------------------------*/
file = &Files[fid];
file->acquire(file, F_WRITE);
/*-------------------------------------------------------------------*/
/* Return error if file is closed. */
/*-------------------------------------------------------------------*/
if (file->ioctl == NULL)
{
set_errno(EBADF);
file->release(file, F_WRITE);
return -1;
}
/*-------------------------------------------------------------------*/
/* Call file system specific write routine. */
/*-------------------------------------------------------------------*/
written = file->write(file, buf, nbytes);
/*-------------------------------------------------------------------*/
/* Set file's errno if less than requested number was written. */
/*-------------------------------------------------------------------*/
if (written < (int)nbytes)
{
file->errcode = get_errno();
if (written == 0)
written = -1;
}
/*-------------------------------------------------------------------*/
/* Release exclusive write access to stream. */
/*-------------------------------------------------------------------*/
file->release(file, F_WRITE);
/*-------------------------------------------------------------------*/
/* Return -1 or actual number of bytes read. */
/*-------------------------------------------------------------------*/
return written;
}
示例12: ACE_TMAIN
//.........这里部分代码省略.........
#if !defined (ACE_LACKS_IOSTREAM_TOTALLY)
ifstream ifstr (ACE_TEXT_ALWAYS_CHAR(get_opt.opt_arg ()));
if (!ifstr.good ())
{
ifstr.close ();
ACE_ERROR_RETURN ((LM_ERROR,
"%s "
"-f %s "
"\n"
"Invalid IOR file nominated"
"\n",
argvw[0],
get_opt.opt_arg ()),
-1);
}
while (!ifstr.eof())
{
ACE_CString aString;
have_some_input = 0;
while (!ifstr.eof ())
{
char ch = 0;
ifstr.get (ch);
if (ifstr.eof () || ch == '\n' || ch == '\r')
break;
aString += ch;
++have_some_input;
}
#else
FILE* ifstr = ACE_OS::fopen (get_opt.opt_arg (), ACE_TEXT ("r"));
if (!ifstr || ferror (ifstr))
{
if (ifstr)
{
ACE_OS::fclose (ifstr);
}
ACE_ERROR_RETURN ((LM_ERROR,
"%s "
"-f %s "
"\n"
"Invalid IOR file nominated"
"\n",
argvw[0],
get_opt.opt_arg ()),
-1);
}
while (!feof (ifstr))
{
char ch;
ACE_CString aString;
have_some_input = 0;
while (!feof (ifstr))
{
ch = ACE_OS::fgetc (ifstr);
if (ch == EOF || ch == '\n' || ch == '\r')
break;
aString += ch;
++have_some_input;
示例13: proc_loc
//.........这里部分代码省略.........
{
rpl_s r;
r.fn = f;
if (f.ends(CONSTWSTR(".h")) || f.ends(CONSTWSTR(".cpp")))
{
//tmp_str_c afn(f);
//CHARz_copy(fnnnn, afn.cstr());
parse_text_file(f,lines);
bool cmnt = false;
int cnt = lines.size();
for(r.ln=0;r.ln<cnt;++r.ln)
{
const wstr_c & l = lines.get(r.ln);
int workindex = 0;
while (findTTT(l, r.txt, r.tag, cmnt, r.left, r.rite, workindex))
{
//Print( FOREGROUND_GREEN, "TTT(%i): %s\n", r.tag, tmp_str_c(r.txt).cstr());
if (r.tag >= 0)
{
int i = used_tags.set(r.tag);
if (i < (used_tags.count()-1))
{
for(const rpl_s &rr : need2rpl)
{
if (rr.tag == r.tag)
{
Print( FOREGROUND_RED, "%s(%i): Tag already used: TTT(%i): %s\n", to_str(rr.fn).cstr(), rr.ln, rr.tag, to_str(rr.txt).cstr());
}
}
Print( FOREGROUND_RED, "%s(%i): Tag already used: TTT(%i): %s\n", to_str(f).cstr(), r.ln, r.tag, to_str(r.txt).cstr());
}
}
need2rpl.add(r);
}
}
}
}
//b.load_from_disk_file(str_c(fn_join(ptl, CONSTWSTR("en.labels.lng"))).as_sptr());
//b.detect();
//lngbp.load(b.as_str<wchar>());
used_tags.sort();
auto getfreetag = [&]()->int {
static int lastchecktag = 0;
tbuf_t<int>::default_comparator dc;
for(aint tmp = 0;used_tags.find_index_sorted(tmp,++lastchecktag, dc););
return lastchecktag;
};
wstr_c prevfile;
bool lneschanged = false;
for (rpl_s & r : need2rpl)
{
if (r.tag <= 0)
{
r.tag = getfreetag();
if (prevfile != r.fn)
{
if (lneschanged)
savelines(prevfile, lines);
lneschanged = false;
parse_text_file(r.fn, lines);
prevfile = r.fn;
}
wstr_c & l = lines.get(r.ln);
l.replace( r.left, r.rite-r.left, CONSTWSTR("TTT(\"") + r.txt + CONSTWSTR("\",") + wmake(r.tag) + CONSTWSTR(")") );
lneschanged = true;
}
}
if (lneschanged)
savelines(prevfile, lines);
need2rpl.sort();
FILE *f = fopen(to_str(fn_join(ptl, CONSTWSTR("en.labels.lng"))), "wb");
swstr_c buf;
//uint16 signa = 0xFEFF;
//fwrite(&signa,2,1,f);
for (const rpl_s & r : need2rpl)
{
buf.set_as_int( r.tag ).append(CONSTWSTR("=")).append(r.txt).append(CONSTWSTR("\r\n"));
ts::str_c utf8 = to_utf8(buf);
fwrite(utf8.cstr(), 1, utf8.get_length(), f);
}
fclose(f);
//getch();
return 0;
}
示例14: opus_decoder_create
void *connection_handler(void *socket_desc) {
FILE *file;
int sock = *(int*) socket_desc;
int read_size;
char *message, client_message[8192];
OggStream* stream = 0;
StreamMap streams;
// start opus
int error;
OpusDecoder *dec;
dec = opus_decoder_create(16000, 1, &error);
if (error != OPUS_OK && dec == NULL) {
puts("ERROR LOADING OPUS");
}
// start pocketsphinx
ps_decoder_t *ps = ps_start();
/* // IF RUN VAD AT SERVER
VadInst* handle = NULL;
if (WebRtcVad_Create(&handle) < 0) puts("Error creating WebRtcVad_Create");
if (WebRtcVad_Init(handle) < 0) puts("Error initializing WebRtcVad_Init");
if (WebRtcVad_set_mode(handle, 3) < 0) puts("Error setting mode WebRtcVad_set_mode");
*/
char * dtdepois;
bool ended = true;
while ((read_size = recv(sock, client_message, 8192, 0)) > 0) {
char otherString[3];
strncpy(otherString, client_message, 3);
if (strcmp(otherString, "#JS") == 0) {
puts("GRAM RECVD. SWITCH");
string str1(client_message);
char *dtgram = current_timestamp();
std::string grampath = "/var/www/speechrtc/voiceserver/" + std::string(dtgram) + ".jsgf";
ofstream file;
file.open(grampath.c_str());
file << str1;
file.close();
jsgf_rule_iter_t *itor;
jsgf_t * gram = jsgf_parse_file(grampath.c_str(), NULL);
jsgf_rule_t * rule;
for (itor = jsgf_rule_iter(gram); itor; itor = jsgf_rule_iter_next(itor)) {
rule = jsgf_rule_iter_rule(itor);
if (jsgf_rule_public(rule))
break;
}
fsg_model_t * m = jsgf_build_fsg(gram, rule, ps_get_logmath(ps), 6.5);
fsg_set_t* fsgset = ps_get_fsgset(ps);
fsg_set_add(fsgset, dtgram , m);
fsg_set_select(fsgset , dtgram );
ps_update_fsgset(ps);
continue;
}
if (strcmp(otherString, "STA") == 0) {
// int _res = ps_start_utt(ps, "goforward");
dtdepois = current_timestamp();
puts(dtdepois);
file = fopen(dtdepois, "wb+");
ended = false;
continue;
}
if (strcmp(otherString, "END") == 0) {
puts("END RECVD");
fclose(file);
FILE *_file = fopen(dtdepois, "rb");
char const *hyp, *uttid;
int32 score;
int rv = ps_decode_raw(ps, _file, dtdepois, -1);
if (rv < 0) puts("error ps_decode_raw");
hyp = ps_get_hyp(ps, &score, &uttid);
if (hyp == NULL) {
puts("Error hyp()");
write(sock, "ERR", strlen("ERR"));
} else {
printf("Recognized: %s\n", hyp);
// envia final hypothesis
write(sock, hyp, strlen(hyp));
}
fclose(_file);
ended = true;
continue;
//.........这里部分代码省略.........
示例15: doOutput
void
VTKXMLExportModule :: doOutput(TimeStep *tStep)
{
if ( !testTimeStepOutput(tStep) ) {
return;
}
#ifdef __VTK_MODULE
vtkSmartPointer<vtkUnstructuredGrid> stream = vtkSmartPointer<vtkUnstructuredGrid>::New();
vtkSmartPointer<vtkPoints> nodes = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkIdList> elemNodeArray = vtkSmartPointer<vtkIdList>::New();
#else
FILE *stream = this->giveOutputStream(tStep);
struct tm *current;
time_t now;
time(&now);
current = localtime(&now);
fprintf(stream, "<!-- TimeStep %e Computed %d-%02d-%02d at %02d:%02d:%02d -->\n", tStep->giveIntrinsicTime(), current->tm_year+1900, current->tm_mon+1, current->tm_mday, current->tm_hour, current->tm_min, current->tm_sec);
fprintf(stream, "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n");
fprintf(stream, "<UnstructuredGrid>\n");
#endif
Domain *d = emodel->giveDomain(1);
Element *elem;
FloatArray *coords;
int nelem = d->giveNumberOfElements();
this->giveSmoother(); // make sure smoother is created
// output nodes Region By Region
int nregions = this->smoother->giveNumberOfVirtualRegions();
int regionDofMans, totalcells;
IntArray mapG2L, mapL2G;
/* loop over regions */
for ( int ireg = 1; ireg <= nregions; ireg++ ) {
if ( ( ireg > 0 ) && ( this->regionsToSkip.contains(ireg) ) ) {
continue;
}
// assemble local->global and global->local region map
// and get number of single cells to process
// the composite cells exported individually
this->initRegionNodeNumbering(mapG2L, mapL2G, regionDofMans, totalcells, d, ireg);
/* start default piece containing all single cell elements
* the elements with composite geometry are assumed to be exported in individual pieces
* after the default one
*/
#ifndef __PARALLEL_MODE
if ( regionDofMans && totalcells ) {
#else
if ( 1 ) {
#endif
#ifdef __VTK_MODULE
for ( int inode = 1; inode <= regionDofMans; inode++ ) {
coords = d->giveNode(mapL2G.at(inode))->giveCoordinates();
int dims = coords->giveSize();
nodes->InsertNextPoint(coords->at(1), dims >= 2 ? coords->at(2) : 0.0, dims >= 3 ? coords->at(3) : 0.0);
}
stream->SetPoints(nodes);
#else
fprintf(stream, "<Piece NumberOfPoints=\"%d\" NumberOfCells=\"%d\">\n", regionDofMans, totalcells);
// export nodes in region as vtk vertices
fprintf(stream, "<Points>\n <DataArray type=\"Float64\" NumberOfComponents=\"3\" format=\"ascii\"> ");
for ( int inode = 1; inode <= regionDofMans; inode++ ) {
coords = d->giveNode( mapL2G.at(inode) )->giveCoordinates();
for ( int i = 1; i <= coords->giveSize(); i++ ) {
fprintf( stream, "%e ", coords->at(i) );
}
for ( int i = coords->giveSize() + 1; i <= 3; i++ ) {
fprintf(stream, "%e ", 0.0);
}
}
fprintf(stream, "</DataArray>\n</Points>\n");
#endif
// output all cells of the piece
int nelemNodes;
IntArray cellNodes;
#ifdef __VTK_MODULE
stream->Allocate(nelem);
#else
fprintf(stream, "<Cells>\n");
// output the connectivity data
fprintf(stream, " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\"> ");
#endif
for ( int ielem = 1; ielem <= nelem; ielem++ ) {
elem = d->giveElement(ielem);
if ( ( ireg > 0 ) && ( this->smoother->giveElementVirtualRegionNumber(ielem) != ireg ) ) {
continue;
}
if ( this->isElementComposite(elem) ) {
continue; // composite cells exported individually
}
//.........这里部分代码省略.........