Hey, I've been working on this problem to read numbers from a text file and store them in an array but for some reason can't get it to work. Any help would be appreciated. the assignment is to implement the markov chain algorithm. I've made the reading part and assigning the array in the main fun() but i keep getting undeclared identifier as an error. Here is the code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "eprintf.h"
enum {
NPREF = 2, /* number of prefix words */
NHASH = 4093, /* size of state hash table array */
MAXGEN = 10000 /* maximum words generated */
};
typedef struct State State;
typedef struct Suffix Suffix;
struct State { /* prefix + suffix list */
char *pref[NPREF]; /* prefix words */
Suffix *suf; /* list of suffixes */
State *next; /* next in hash table */
};
struct Suffix { /* list of suffixes */
char *word; /* suffix */
Suffix *next; /* next in list of suffixes */
};
State *lookup(char *prefix[], int create);
void build(char *prefix[], FILE*);
void generate(int nwords);
void add(char *prefix[], char *word);
State *statetab[NHASH]; /* hash table of states */
char NONWORD[] = "\n"; /* cannot appear as real word */
//FILE* random_reader;
//FILE* myfile;
/* markov main: markov-chain random text generation */
int main(void)
{
int i, nwords = MAXGEN;
char *prefix[NPREF]; /* current input prefix */
FILE* random_reader;
FILE* myfile;
int c;
//long seed;
setprogname("markov");
//seed = time(NULL);
//srand(seed);
random_reader = fopen("../random_num.txt","r");
myfile = fopen("../alice30.txt","r");
int element;
int random_num[10000];
char line; //each number
int i=0;
while(fgets(line, 20, random_reader)!=NULL) // update the array
{
sscanf(line,"%o",&element);
random_num[i]=element;
i++;
}
for (i = 0; i < NPREF; i++) /* set up initial prefix */
prefix[i] = NONWORD;
build(prefix, stdin);
add(prefix, NONWORD);
generate(nwords);
return 0;
}
const int MULTIPLIER = 31; /* for hash() */
/* hash: compute hash value for array of NPREF strings */
unsigned int hash(char *s[NPREF])
{
unsigned int h;
unsigned char *p;
int i;
h = 0;
for (i = 0; i < NPREF; i++)
for (p = (unsigned char *) s[i]; *p != '\0'; p++)
h = MULTIPLIER * h + *p;
return h % NHASH;
}
/* lookup: search for prefix; create if requested. */
/* returns pointer if present or created; NULL if not. */
/* creation doesn't strdup so strings mustn't change later. */
State* lookup(char *prefix[NPREF], int create)
{
int i, h;
State *sp;
h = hash(prefix);
for (sp = statetab[h]; sp != NULL; sp = sp->next) {
for (i = 0; i < NPREF; i++)
if (strcmp(prefix[i], sp->pref[i]) != 0)
break;
if (i == NPREF) /* found it */
return sp;
}
if (create) {
sp = (State *) emalloc(sizeof(State));
for (i = 0; i < NPREF; i++)
sp->pref[i] = prefix[i];
sp->suf = NULL;
sp->next = statetab[h];
statetab[h] = sp;
}
return sp;
}
/* addsuffix: add to state. suffix must not change later */
void addsuffix(State *sp, char *suffix)
{
Suffix *suf;
suf = (Suffix *) emalloc(sizeof(Suffix));
suf->word = suffix;
suf->next = sp->suf;
sp->suf = suf;
}
/* add: add word to suffix list, update prefix */
void add(char *prefix[NPREF], char *suffix)
{
State *sp;
sp = lookup(prefix, 1); /* create if not found */
addsuffix(sp, suffix);
/* move the words down the prefix */
memmove(prefix, prefix+1, (NPREF-1)*sizeof(prefix[0]));
prefix[NPREF-1] = suffix;
}
/* build: read input, build prefix table */
void build(char *prefix[NPREF], FILE *f)
{
char buf[100], fmt[10];
/* create a format string; %s could overflow buf */
sprintf(fmt, "%%%ds", sizeof(buf)-1);
while (fscanf(f, fmt, buf) != EOF)
add(prefix, estrdup(buf));
}
/* generate: produce output, one word per line */
void generate(int nwords)
{
State *sp;
Suffix *suf;
char *prefix[NPREF], *w;
int i, nmatch;
for (i = 0; i < NPREF; i++) /* reset initial prefix */
prefix[i] = NONWORD;
for (i = 0; i < nwords; i++) {
sp = lookup(prefix, 0);
if (sp == NULL)
eprintf("internal error: lookup failed");
nmatch = 0;
for (suf = sp->suf; suf != NULL; suf = suf->next)
if (rand() % ++nmatch == 0) /* prob = 1/nmatch */
w = suf->word;
if (nmatch == 0)
eprintf("internal error: no suffix %d %s", i, prefix[0]);
if (strcmp(w, NONWORD) == 0)
break;
printf("%s\n", w);
memmove(prefix, prefix+1, (NPREF-1)*sizeof(prefix[0]));
prefix[NPREF-1] = w;
}
}
******* Here are the eprintf header file**************
/* eprintf.h: error wrapper functions */
extern void eprintf(char *, ...);
extern void weprintf(char *, ...);
extern char *estrdup(char *);
extern void *emalloc(size_t);
extern void *erealloc(void *, size_t);
extern char *progname(void);
extern void setprogname(char *);
#define NELEMS(a) (sizeof(a) / sizeof(a[0]))
*******here is the eprintf source file*********
#include <stdio.h>
#include <stdlib.h>
#include "eprintf.h"
#include <stdarg.h>
#include <string.h>
#include <errno.h>
static char *name = NULL; /* program name for messages */
/* eprintf: print error message and exit */
void eprintf(char *fmt, ...)
{
va_list args;
fflush(stdout);
if (progname() != NULL)
fprintf(stderr, "%s: ", progname());
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (fmt[0] != '\0' && fmt[strlen(fmt)-1] == ':')
fprintf(stderr, " %s", strerror(errno));
fprintf(stderr, "\n");
exit(2); /* conventional value for failed execution */
}
/* weprintf: print warning message */
void weprintf(char *fmt, ...)
{
va_list args;
fflush(stdout);
fprintf(stderr, "warning: ");
if (progname() != NULL)
fprintf(stderr, "%s: ", progname());
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (fmt[0] != '\0' && fmt[strlen(fmt)-1] == ':')
fprintf(stderr, " %s\n", strerror(errno));
else
fprintf(stderr, "\n");
}
/* emalloc: malloc and report if error */
void *emalloc(size_t n)
{
void *p;
p = malloc(n);
if (p == NULL)
eprintf("malloc of %u bytes failed:", n);
return p;
}
/* erealloc: realloc and report if error */
void *erealloc(void *vp, size_t n)
{
void *p;
p = realloc(vp, n);
if (p == NULL)
eprintf("realloc of %u bytes failed:", n);
return p;
}
/* estrdup: duplicate a string, report if error */
char *estrdup(char *s)
{
char *t;
t = (char *) malloc(strlen(s)+1);
if (t == NULL)
eprintf("estrdup(\"%.20s\") failed:", s);
strcpy(t, s);
return t;
}
/* progname: return stored name of program */
char *progname(void)
{
return name;
}
/* setprogname: set stored name of program */
void setprogname(char *str)
{
name = estrdup(str);
}
It is very important that you read compiler error message from the top down. You got 3 C2143 errors before you got the C2065 error. It is typical that error messages get less accurate and informative, an earlier error may produce a slew of additional errors. The first message complains about the element variable declaration. Then you get additional errors for any line that contains element since the compiler couldn't properly parse the declaration.
Your compiler requires you to put all variable declarations before the code that uses them.
Also note that you've got two declarations for the i variable. And that line needs to be an array of char: char line[20]; Moving the file reading code into a separate function would be a rather good idea.
In main() you have variable definitions appearing after code. This is permissible in C99 but not in C89, so if you're using an old C89 compiler, or something like MSVC which still doesn't support C99, then this is not going to compile. Move this block:
int element;
int random_num[10000];
char line; //each number
int i=0;
up above the code before it so that your variable definitions precede any actual code.
Related
I'm trying to build an ancient version of the ls command (written in pre-ANSI/ISO C). But I'm getting a lot of warnings, which for most of these I can fix, however I also get a few errors. This is one of them: error: conflicting types for ‘malloc’; have ‘char *()’
This is the affected part of the program:
static char sccsid[] = "#(#)ls.c 1.21";
/*
* list file or directory;
* define DOTSUP to suppress listing of files beginning with dot
*/
#include <sys/param.h>
#include <sys/types.h>
#include <sys/sysmacros.h>
#include <sys/stat.h>
#include <sys/dir.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef STANDALONE
#define TERMINFO
#endif
/* -DNOTERMINFO can be defined on the cc command line to prevent
* the use of terminfo. This should be done on systems not having
* the terminfo feature (pre 6.0 sytems ?).
* As a result, columnar listings assume 80 columns for output,
* unless told otherwise via the COLUMNS environment variable.
*/
#ifdef NOTERMINFO
#undef TERMINFO
#endif
#ifdef TERMINFO
#include <curses.h>
#include <term.h>
#endif
#define DOTSUP 1
#define ISARG 0100000 /* this bit equals 1 in lflags of structure lbuf
* if *namep is to be used;
*/
#define DIRECT 10 /* Number of direct blocks */
#ifdef u370
/* Number of pointers in an indirect block */
#define INDIR (BSIZE/sizeof(daddr_t))
/* Number of right shifts to divide by INDIR */
#define INSHFT 10
#else
/* Number of pointers in an indirect block */
#define INDIR 128
/* Number of right shifts to divide by INDIR */
#define INSHFT 7
#endif
struct lbuf {
union {
char lname[DIRSIZ]; /* used for filename in a directory */
char *namep; /* for name in ls-command; */
} ln;
char ltype; /* filetype */
unsigned short lnum; /* inode number of file */
short lflags; /* 0777 bits used as r,w,x permissions */
short lnl; /* number of links to file */
unsigned short luid;
unsigned short lgid;
long lsize; /* filesize or major/minor dev numbers */
long lmtime;
};
struct dchain {
char *dc_name; /* path name */
struct dchain *dc_next; /* next directory in the chain */
};
struct dchain *dfirst; /* start of the dir chain */
struct dchain *cdfirst; /* start of the durrent dir chain */
struct dchain *dtemp; /* temporary - used for linking */
char *curdir; /* the current directory */
int nfiles = 0; /* number of flist entries in current use */
int nargs = 0; /* number of flist entries used for arguments */
int maxfils = 0; /* number of flist/lbuf entries allocated */
int maxn = 0; /* number of flist entries with lbufs assigned */
int quantn = 1024; /* allocation growth quantum */
struct lbuf *nxtlbf; /* pointer to next lbuf to be assigned */
struct lbuf **flist; /* pointer to list of lbuf pointers */
struct lbuf *gstat();
FILE *pwdfu, *pwdfg, *dirf;
int aflg, bflg, cflg, dflg, fflg, gflg, iflg, lflg, mflg;
int nflg, oflg, pflg, qflg, sflg, tflg, uflg, xflg;
int Cflg, Fflg, Rflg;
int rflg = 1; /* initialized to 1 for special use in compar() */
int flags;
int err = 0; /* Contains return code */
char *dmark; /* Used if -p option active. Contains "/" or NULL. */
unsigned lastuid = -1, lastgid = -1;
int statreq; /* is > 0 if any of sflg, (n)lflg, tflg are on */
char *dotp = ".";
char *makename();
char tbufu[16], tbufg[16]; /* assumed 15 = max. length of user/group name */
char *ctime();
long nblock();
long tblocks; /* total number of blocks of files in a directory */
long year, now;
int num_cols = 80;
int colwidth;
int filewidth;
int fixedwidth;
int curcol;
int compar();
int new_line()
{
if (curcol) {
putc('\n',stdout);
curcol = 0;
}
}
int pprintf(char *s1, char *s2)
{
register char *s;
register int c;
register int cc;
int i;
for (s = s1, i = 0; i < 2; i++, s = s2)
while(c = *s++) {
if (c < ' ' || c >= 0177) {
if (qflg)
c = '?';
else if (bflg) {
curcol += 3;
putc ('\\', stdout);
cc = '0' + (c>>6 & 07);
putc (cc, stdout);
cc = '0' + (c>>3 & 07);
putc (cc, stdout);
c = '0' + (c & 07);
}
}
curcol++;
putc(c, stdout);
}
}
/*
* pdirectory: print the directory name, labelling it if title is
* nonzero, using lp as the place to start reading in the dir.
*/
int pdirectory (char *name, int title, int lp)
{
register struct dchain *dp;
register struct lbuf *ap;
register char *pname;
register int j;
filewidth = 0;
curdir = name;
if (title) {
putc('\n', stdout);
pprintf(name, ":");
new_line();
}
nfiles = lp;
readdir(name);
if (fflg==0)
qsort(&flist[lp],(unsigned)(nfiles - lp),sizeof(struct lbuf *),compar);
if (Rflg) for (j = nfiles - 1; j >= lp; j--) {
ap = flist[j];
if (ap->ltype == 'd' && strcmp(ap->ln.lname, ".") &&
strcmp(ap->ln.lname, "..")) {
dp = (struct dchain *)calloc(1,sizeof(struct dchain));
if (dp == NULL)
fprintf(stderr,"ls: out of memory\n");
pname = makename(curdir, ap->ln.lname);
dp->dc_name = (char *)calloc(1,strlen(pname)+1);
if (dp->dc_name == NULL) {
fprintf(stderr,"ls: out of memory\n");
free(dp);
}
else {
strcpy(dp->dc_name, pname);
dp -> dc_next = dfirst;
dfirst = dp;
}
}
}
if (lflg || sflg)
curcol += printf("total %ld", tblocks);
pem(&flist[lp],&flist[nfiles],lflg||sflg);
}
int main(int argc, char **argv)
{
extern char *optarg;
extern int optind;
int amino, opterr=0;
int c;
register struct lbuf *ep;
struct lbuf lb;
int i, width;
long time();
char *malloc();
void qsort(), exit();
malloc is declared in stdlib.h as :
void *malloc(size_t size);
You code wrongly re-declares it as:
char *malloc();
Remove the wrong re-declaration and review use of malloc() carefully.
I'm trying to store strings into dynamical allocated memory. I'm able to break the strings down and store them within the members of the struct and print them perfectly within the function readFile, but when it comes to printing it in main, it's only printing the last scan and everything else is null. I'm thinking that maybe I'm not allocating the array of structures correctly. Here's my program.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifdef _MSC_VER
#include <crtdbg.h> // needed to check for memory leaks (Windows only!)
#endif
#define MEM_ERROR printf("Not enough memory\n")
#define FLUSH while( getchar() != '\n' )
typedef struct
{
char id[5];
char *name;
int *sales;
int total;
int low;
int high;
}PERSON;
typedef struct
{
int worker;
int weeks;
PERSON *pAry;
}HEADER;
// Function Declaration
void valiFile(char nameIn[]);
FILE* openFile(char nameIn[]);
void getHeader(FILE* fpFile, HEADER *pHead);
PERSON* aloPerson(int workers);
void readFile(FILE* fpFile, HEADER *pHead);
char* aloName(HEADER *pHead, int strCount);
void repeat(char nameIn[]);
int main ( void )
{
// Local Declaration
FILE* fpFile;
char nameIn[25];
char *endPro = "end";
HEADER *pHead = (HEADER*)calloc(1, sizeof(HEADER));
// Statement
printf("Please select file to to open.\nsales or sales_2: ");
scanf("%s", nameIn);
FLUSH;
do
{
valiFile(nameIn);
fpFile = openFile(nameIn);
getHeader(fpFile, pHead);
readFile(fpFile, pHead);
//printf("%s\n", pHead->pAry[0].id);
//free(pHead);
repeat(nameIn);
}
return 0;
}// main
/* ========== valiFile ==========
========== */
void valiFile(char nameIn[])
{
// Local Declaration
char *file = "sales";
char *file2 = "sales_2";
int i;
int check = 0;
// Statement
do
{
for(i = 0; nameIn[i]; i++)
{
nameIn[i] = tolower(nameIn[i]);
}
if(strcmp(file, nameIn) != 0)
{
if(strcmp(file2, nameIn) != 0)
{
printf("\nPlease enter a valid file.\n");
printf("sales or sales_2: ");
scanf("%s", nameIn);
FLUSH;
}
else
check = 1;
}
else
check = 1;
}
while(check != 1)
;
return;
}// valiFile
/* ========== openFile ==========
========== */
FILE* openFile(char nameIn[])
{
// Local Declaration
FILE* fpFile;
char *strSale = "sales";
// Statement
if(strcmp(strSale, nameIn) == 0)
{
fpFile = fopen("sales.txt", "r");
if(fpFile == NULL)
{
printf("File didn't read correcty.\n");
exit(100);
}
}
else
{
fpFile = fopen("sales_2.txt", "r");
if(fpFile == NULL)
{
printf("File didn't read correcty.\n");
exit(100);
}
}
return fpFile;
}// openFile
/* ========================= getHeader ========================
============================================================*/
void getHeader(FILE* fpFile, HEADER *pHead)
{
// Local Declaration
int worker, salesWeek, i;
PERSON *list;
// Statement
fscanf(fpFile, "%d %d", &worker, &salesWeek);
list = aloPerson(worker);
HEADER header = {worker, salesWeek, list};
*pHead = header;
return;
}// getHeader
/* aloPerson
*/
PERSON* aloPerson(int worker)
{
// Local Declaration
PERSON *list;
// Statement
list =(PERSON*)calloc(worker, sizeof(PERSON));
if(list == NULL)
{
MEM_ERROR, exit(103);
}
return list;
}// aloPerson
/* readFile
*/
void readFile(FILE* fpFile, HEADER *pHead)
{
// Local Declaration
char temp[50];
int strCount = 0;
char *loc;
char *ptr;
int i;
// Statement
fscanf(fpFile, "%*d %*d");
for(i = 0; i < pHead->worker; i++)
{
while(fgets(temp, sizeof(temp), fpFile))
{
ptr = temp;
loc = strchr(temp, ' ');
strncpy(pHead->pAry[i].id, temp, (loc - ptr));
ptr += (loc - temp);
*ptr++;
loc = strchr(temp, ';');
strCount = (loc - ptr);
pHead->pAry[i].name = aloName(pHead, strCount);
strncpy(pHead->pAry[i].name, ptr, (loc - ptr));
ptr += (loc - ptr);
printf("%s\n", pHead->pAry[i].name);
}
}
return;
}// readFile
/* aloName
*/
char* aloName(HEADER *pHead, int strCount)
{
// Local Declaration
char *names;
// Statement;
names = malloc((strCount + 1)*sizeof(char));
return names;
}
Below is my code:
I cant seem to use qsort effectively... It turns my array into 0's after they are populated with names and start times... Is it a problem with my qsort call? or the qsort itself.
The header with the structures is as follows:
/**
* Simulation of a process scheduler
*/
//#ifndef SCHEDULER_H_
#define SCHEDULER_H_
#include <stddef.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
/* types */
/** units of time */
typedef long time;
/** process identifier */
typedef int pid;
/** Information about a job of interest to the task scheduler */
struct job_data {
/* pid of this process */
pid pid;
/* time process starts */
time start;
/* time needed to finish */
time finish;
/* time spent processing so far */
time scheduled;
/* Number of lines */
int lines;
};
struct job {
/* Various parameters used by the scheduler */
char job_id[20];
struct job_data parameters;
char *lines[20];
};
/* I/O Files */
//static char *inputFile;
char * in;
static FILE *input;
static FILE *cur;
/*Scheduled jobs indexed by PID*/
struct job list[20];
/* the next job to schedule */
//static struct job *job_next = NULL;
/* Time */
time clock;
/*Comparison for qsort*/
int compare_start(const void *x, const void *y)
{
const struct job *a = x;
const struct job *b = y;
printf("%ld, %ld\n", a->parameters.start, b->parameters.start);
if (a->parameters.start < b->parameters.start)
{
return -1;
}
if (a->parameters.start > b->parameters.start)
{
return 1;
}
return 0;
}
/*Order Jobs*/
static void order_jobs(void)
{
qsort(list, (sizeof list) / (sizeof list[0]), sizeof list[0], compare_start);
}
/** Read and parse input from input file */
static void parse_input(void)
{
char buffer[BUFSIZ];
char lines[BUFSIZ];
int jobs = 0;
struct job *current;
while( fgets(buffer, sizeof(buffer), input) )
{
time start;
char buf[BUFSIZ];
sscanf(buffer,"./%s/", buf);
cur = fopen(buf, "r" );
int n_lines = 0;
while( fgets(lines, sizeof(lines), cur) )
{
if( n_lines == 0 )
{
current = &list[jobs];
strcpy(current->job_id, buf);
sscanf(lines,"%ld", &start);
current->parameters.start = start;
}
n_lines++;
}
current->parameters.lines = n_lines;
jobs++;
fclose(cur);
}
order_jobs();
for (int i = 0; i < jobs; i++)
{
printf("%s %ld %d\n", list[i].job_id, list[i].parameters.start, list[i].parameters.lines);
}
}
int main(int argc, char **argv)
{
in = argv[1];
if ( (input = fopen(in, "r")) == NULL ) {
fprintf(stderr, "cannot open %s\n", argv[1]);
}
parse_input();
fclose(input);
return EXIT_SUCCESS;
}
You only load jobs entries into the array, but you tell qsort() to sort the entire array (20 elements). This probably puts non-initialized elements at the front, which you then print.
I'm new to C programming. I want to create circular buffer which writes strings into text file.
#include <stdio.h>
#include <malloc.h>
// Buffer writer header files
#include <stdlib.h>
typedef struct { char value; } ElemType;
/* Circular buffer object */
typedef struct {
int size; /* maximum number of elements */
int start; /* index of oldest element */
int end; /* index at which to write new element */
ElemType *elems; /* vector of elements */
} CircularBuffer;
void cbInit(CircularBuffer *cb, int size);
void cbFree(CircularBuffer *cb);
int cbIsFull(CircularBuffer *cb);
int cbIsEmpty(CircularBuffer *cb);
void cbWrite(CircularBuffer *cb, ElemType *elem);
void cbRead(CircularBuffer *cb, ElemType *elem);
void writeFile();
void cbInit(CircularBuffer *cb, int size) {
cb->size = size + 1; /* include empty elem */
cb->start = 0;
cb->end = 0;
cb->elems = (ElemType *)calloc(cb->size, sizeof(ElemType));
}
void cbFree(CircularBuffer *cb) {
free(cb->elems); /* OK if null */ }
int cbIsFull(CircularBuffer *cb) {
return (cb->end + 1) % cb->size == cb->start; }
int cbIsEmpty(CircularBuffer *cb) {
return cb->end == cb->start; }
/* Write an element, overwriting oldest element if buffer is full. App can
choose to avoid the overwrite by checking cbIsFull(). */
void cbWrite(CircularBuffer *cb, ElemType *elem) {
cb->elems[cb->end] = *elem;
cb->end = (cb->end + 1) % cb->size;
if (cb->end == cb->start)
cb->start = (cb->start + 1) % cb->size; /* full, overwrite */
}
/* Read oldest element. App must ensure !cbIsEmpty() first. */
void cbRead(CircularBuffer *cb, ElemType *elem) {
*elem = cb->elems[cb->start];
cb->start = (cb->start + 1) % cb->size;
}
int mainSecond(int argc, char **argv) {
CircularBuffer cb;
ElemType elem = {0};
int testBufferSize = 10; /* arbitrary size */
cbInit(&cb, testBufferSize);
/* Fill buffer with test elements 3 times */
for (elem.value = 0; elem.value < 3 * testBufferSize; ++ elem.value)
cbWrite(&cb, "AC");
/* Remove and print all elements */
while (!cbIsEmpty(&cb)) {
cbRead(&cb, &elem);
printf("%d\n", elem.value);
}
cbFree(&cb);
return 0;
}
int main(int argc, char** argv) {
writeFile();
return 0;
}
// write to file function
void writeFile() {
FILE *file;
file = fopen("file.txt", "a+"); /* apend file (add text to a file or create a file if it does not exist.*/
CircularBuffer cb;
ElemType elem = {0};
int testBufferSize = 10; /* arbitrary size */
cbInit(&cb, testBufferSize);
/* Fill buffer with test elements 3 times */
for (elem.value = 0; elem.value < 3 * testBufferSize; ++ elem.value)
cbWrite(&cb, "test");
/* Remove and print all elements */
while (!cbIsEmpty(&cb)) {
cbRead(&cb, &elem);
fprintf(file, "%d\n", elem.value);
// printf("%d\n", elem.value);
}
// write something into the file
fprintf(file, "%s", "Test!\n");
// close the file
fclose(file);
//getchar(); /* pause and wait for key */
cbFree(&cb);
}
The question is how I can insert Strings into the circular buffer and after that write them into text file? This implementation only works with numbers.
There are two ways:
Insert pointers in the circular buffer. You would store your string somewhere in memory. Then you have a pointer to that place in memory, that you store in your circular buffer.
Store characters in your circular buffer, in such a way that concatenating them results in strings. This means that the strings are copied into your buffer, and you need some way to read enough characters out of the buffer to make up a string.
Im making an application that uses of API-threads in C, The program takes N-files (N>2) with names disordered,per each file is generated a thread of execution which sort the files using the function qsort, after being ordered files, each thread should create a file keeping the original file intact and displaying the sorted file to another file with the extension <.sorted>. The program sorts the numbers without problems, even if I put standard output displays the result on screen, but when I try to create the output file with extension .sorted the program breaks out.
this is my code file.c
#include <stdio.h> /* Standard buffered input/output */
#include <stdlib.h> /* Standard library functions */
#include <string.h> /* String operations */
#include <pthread.h> /* Thread related functions */
#include "pf1.h" /* Header specific to this app */
pthread_attr_t attr;
void *thread_worker(void *name_file)
{
FILE *entrada, *salida;
char* nombres = (char*)name_file;
int numero;
char temp [10000];
int i;
stats_t estadisticas;
printf ("File_name:%s\n", nombres);
entrada = fopen(nombres, "r");
salida = fopen (strcat(nombres, ".sorted"), "w");
while (!feof(entrada)){
fscanf (entrada, "%s\n",temp);
numero++;
}
char* lista[numero]; //array to sort the file
rewind (entrada);
for (i=0;i<numero;i++)
{
fscanf(entrada," %[^\n]", temp);
lista[i] = (char*)malloc((strlen(temp)+1)*sizeof(char));
strcpy(lista[i], temp);
}
size_t large = sizeof(lista) / sizeof(char *);
qsort(lista,large ,sizeof(char *) ,cstring_cmp );
printf ("Archivo Ordenado\n", i+1);
for (i=0;i<large;i++)
printf("%s\n",lista[i]);
pthread_exit(NULL);
}
int main(int argc, char *argv [])
{
stats_t **stats;
int i, rc;
pthread_t my_threads[argc-1];
pthread_attr_init(&attr);
if (argc <3) {
printf ("|files| > 2\n");
}else{
printf("files to sorted: %d\n", argc - 1);
for (i = 1; i < argc; i++){
//printf("%s%s\n", argv[i], (i < argc-1) ? " " : "");
rc = pthread_create(&my_threads[i], &attr, thread_worker, (void *)argv[i]);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n",rc);
return -1;
}
}
}
return 0;
} /*end main */
this is mi file.h
#ifndef PF1_H_
#define PF1_H_
typedef struct _stats_t
{
char *longest, *shortest;
unsigned int numlines;
} stats_t;
int cstring_cmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return -strcasecmp(*ia, *ib);
/* strcmp functions works exactly as expected from
comparison function */
}
void print_cstring_array(char **array, size_t len)
{
size_t i;
for(i=0; i<len; i++)
printf("%s | ", array[i]);
putchar('\n');
}
#endif /* PF1_1_H_ */
I would like some help with this problem because I can not see which is the fault ... thanks to all in advance and excuse my English
This line here may be your problem:
salida = fopen (strcat(nombres, ".sorted"), "w");
From what I can tell, that nombres variable is coming from argv. Since you're not the one allocating memory for argv, you don't know that there will be extra space for the ".sorted" (and there probably won't be). If you strcpy it to your own buffer with space for the ".sorted", you should be fine.
#define EXT_LEN 7
#define MAX_TOTAL_LEN 250
#define MAX_FILE_LEN 242 //MAX_TOTAL_LEN - EXT_LEN - 1
char *name_ptr;
char nombres[MAX_TOTAL_LEN];
int len;
name_ptr = (char*)name_file;
len = strlen(name_ptr);
if (len > MAX_FILE_LEN) {
len = MAX_FILE_LEN;
}
strncpy(nombres, name_ptr, len);
strcpy(nombres+len, ".sorted");
salida = fopen (nombres, "w");
I once had issues about not passing an int identifier while calling thread execution functions. Try building a struct with both an integer identifier and the filename, then pass it as a parameter to your thread_worker() function.