This is my code
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct {
int M,N;
int min,max;
int width;
int height;
unsigned char **pixels;
}PPMIMG;
int fnReadPPM(char* fileNm,PPMIMG* img);
int main(int argc, char ** argv)
{
PPMIMG img;
if(fnReadPPM(argv[1], &img) != FALSE)
{
return TRUE;
}
return 0;
}
int fnReadPPM(char* fileNm ,PPMIMG* img)
{
FILE* fp;
fp = fopen("/users/ashton/Downloads/test.txt","rb");
if(fileNm == NULL){
fprintf(stderr,"Unable to File ! : %s\n",fileNm);
return FALSE;
}
fclose(fp);
return TRUE;
}
int fnWritePPM(char* fileNm, PPMIMG* img)
{
FILE *fp =fopen(fileNm, "w");
if(fp == NULL)
{
fprintf(stderr, "Failed to create the file.");
return FALSE;
}
return TRUE;
}
This is the error code:
Unable to File ! : (null)
Program ended with exit code: 0
Your wrongly test the fopen return value:
fp = fopen("/users/ashton/Downloads/test.txt","rb");
if (fp == NULL) { //<===== Was WRONG, you used fileNm instead of fp
perror("Unable to File");
return FALSE;
}
The problem ist most likely here:
int fnReadPPM(char* fileNm ,PPMIMG* img)
{
FILE* fp;
fp = fopen("/users/ashton/Downloads/test.txt","rb"); // you assign fp
if (fileNm == NULL){ // and here you check for fileNm
fprintf(stderr,"Unable to File ! : %s\n",fileNm);
return FALSE;
}
...
You want this:
int fnReadPPM(char* fileNm ,PPMIMG* img)
{
FILE* fp;
fp = fopen("/users/ashton/Downloads/test.txt","rb");
if (fp == NULL) {
fprintf(stderr,"Unable to open file %s.\n", fileNm);
return FALSE;
}
...
However in the fnWritePPM function you did it right.
Related
it's a cesar encrypt in process
the problem is when i open a file with the method "openFile"
/* it's been 2 years since I've touched the c language, I'm getting back to it */
i have this code other file :
//method to encrypt a char
char encrypt(char c, int jump) {
int overflow = 0;
char res = c;
char tabChars[26] = {'a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p','q',
'r','s','t','u','v','w','x','y','z'};
for(int i=0;i<sizeof (tabChars);i++) {
if(c == tabChars[i]) {
if(i+jump > 25) {
overflow = i+jump - 26;
res = tabChars[overflow];
} else if(i+jump <= 25) {
res = tabChars[i+jump];
}
}
}
return res;
};
void writeInFile(FILE* file) {
//todo
};
// error here
void openFile(char* file) {
FILE* f = fopen(file, "r");
printf("\nopen file : %s\n", file);
char c;
while((c = getc(f)) != EOF) {
putchar(c);
}
fclose(f);
};
and main code :
int jump = 5;
char c = 't';
printf("\nletter change with : --%c--\n",encrypt(c,jump));
char* file = "taget/to/message.txt";
openFile(file); // error here
but i have a error :
Invalid parameter passed to C runtime function.
Invalid parameter passed to C runtime function.
why doesn't work ? thanks all
with if(f) // works, thx all for your comments
void openFile(char* file) {
FILE* f = fopen(file, "r");
if(f) {
printf("\nopen file : %s\n", file);
char c;
while((c = getc(f)) != EOF) {
putchar(c);
}
fclose(f);
} else {
printf("\nopen error...\n");
}
};
out of function :
I need to write separate functions for opening/closing the file and working with it. Was recommended to not use global variables in it.
I have a function where I need to open the file and print what's in it(open_file), a second to work with the data in it(do_stuff_in_file), and a third to only close the file and exit the program(close_file).
When I try to call do_stuff_in_file or close_file the program just crashes.
I know I'm supposed to use pointers, but I just can't get it right and I don't know where's the mistake.
int open_file(FILE **fr) {
if ((fr = fopen("soldcars.txt", "r")) == NULL) {
printf("File was not opened\n");
return 1;
}
else {
char testchar;
while ((testchar = fgetc(fr)) != EOF) {
ungetc(testchar, fr);
//just printing whats in the file
}
}
return 0;
}
int do_stuff_in_file(FILE **fr, int date) {
if (fr==NULL) {
printf("File not open yet\n");
return 1;
}
else{ fseek(fr, 0, SEEK_SET); } //doing stuff
return 0;
}
int close_file(FILE **fr) {
if (fr==NULL) {
printf("It was not even open yet\n");
return 1;
}
else{
if (fclose(fr) == EOF) {
printf("File was not successfully closed");
return 1;
}
else{
printf("Adios");
exit(1);
}
}
}
int main() {
char input;
int date;
FILE* fr;
fr = NULL;
while ((input = getchar()) != 'c') {
if (input == 'o') open_file(&fr);
else if (input == 'd') {
scanf("%d", &date);
do_stuff_in_file(&fr, date);
}
}
if (input == 'c') {
close_file(&fr);
}
return 0;
}
You need to dereference properly. eg
int open_file(FILE **fr) {
if ((*fr = fopen("soldcars.txt", "r")) == NULL) {
perror( "soldcars.txt" );
return 1;
}
Note *fr = open instead of fr = open. And, in that function, always use *fr, as in fgetc(*fr) vice fgetc(fr). Similarly in the other functions. Because fr is not a FILE *, but *fr is.
I am trying to implement multiple clients and multiple servers using Sun-RPC. However, I am unable to run multiple servers at the same time to begin with.
Here's the IDL
const MAXLEN = 1024;
typedef string filename<MAXLEN>;
typedef int vtimestamp[5];
typedef int sender_id;
typedef int recv_id;
struct request {
filename name;
int start;
vtimestamp ts;
sender_id sid;
recv_id rid;
};
typedef struct request request;
typedef opaque filepart[MAXLEN];
struct partreceive {
filepart data;
int bytes;
vtimestamp ts;
sender_id sid;
recv_id rid;
};
typedef struct partreceive partreceive;
struct partsend {
filename name;
filepart data;
int bytes;
vtimestamp ts;
sender_id sid;
recv_id rid;
};
typedef struct partsend partsend;
union readfile_res switch (int errno) {
case 0:
partreceive part;
default:
void;
};
program FTPROG {
version FTVER {
readfile_res retrieve_file(request *) = 1;
int send_file(partsend *) = 2;
} = 1;
} = 0x31240000;
Here's the server 1's code:
#include <rpc/rpc.h>
#include <stdio.h>
#include "maekawa.h"
extern __thread int errno;
int Id = 1;
char fileLog[50] = "server_1_file_log.txt";
int cur_ts[5] = {0};
readfile_res* retrieve_file_1_svc(request *req, struct svc_req *rqstp)
{
printf("%d",req->rid);
if(req->rid == Id)
{
FILE *file;
char data[1024];
int bytes,i;
static readfile_res res;
//update the timestamp
for(i=0;i<5;i++)
cur_ts[i] = res.readfile_res_u.part.ts[i];
char fn[3*MAXLEN] = "storage/";
strcat(fn,req->name);
file = fopen(fn, "rb");
if (file == NULL)
{
res.errno = errno;
return (&res);
}
fseek (file, req->start, SEEK_SET);
bytes = fread(res.readfile_res_u.part.data, 1, 1024, file);
res.readfile_res_u.part.bytes = bytes;
res.readfile_res_u.part.sid = Id;
res.readfile_res_u.part.rid = req->sid;
res.errno = 0;
fclose(file);
//log the transaction
FILE *log = NULL;
log = fopen(fileLog, "a");
fprintf(log,"R,");
for(i=0;i<5;i++)
fprintf(log,"%d,",cur_ts[i]);
fprintf(log,"%d,",req->sid);
fprintf(log,"%s,",req->name);
fprintf(log,"%d\n",req->start);
fclose(log);
return (&res);
}
}
int* send_file_1_svc(partsend *rec, struct svc_req *rqstp)
{
int i;
printf("%d",rec->rid);
if(rec->rid == Id)
{
FILE *file;
int write_bytes;
static int result;
cur_ts[Id]++;
//update the timestamp
for(i=0;i<5;i++)
cur_ts[i] = rec->ts[i];
char fn[3*MAXLEN] = "storage/";
strcat(fn,rec->name);
file = fopen(fn, "a");
if (file == NULL) {
result = errno;
return &result;
}
write_bytes = fwrite(rec->data, 1, rec->bytes, file);
fclose(file);
result = 0;
//log the transaction
FILE *log = NULL;
log = fopen(fileLog, "a");
fprintf(log,"S,");
for(i=0;i<5;i++)
fprintf(log,"%d,",cur_ts[i]);
fprintf(log,"%d,",rec->sid);
fprintf(log,"%s\n",rec->name);
fclose(log);
return &result;
}
}
Here's Server 2 :
#include <rpc/rpc.h>
#include <stdio.h>
#include "maekawa.h"
extern __thread int errno;
int Id = 2;
char fileLog[50] = "server_2_file_log.txt";
int cur_ts[5] = {0};
readfile_res* retrieve_file_1_svc(request *req, struct svc_req *rqstp)
{
printf("%d",req->rid);
if(req->rid == Id)
{
FILE *file;
char data[1024];
int bytes,i;
static readfile_res res;
//update the timestamp
for(i=0;i<5;i++)
cur_ts[i] = res.readfile_res_u.part.ts[i];
char fn[3*MAXLEN] = "storage/";
strcat(fn,req->name);
file = fopen(fn, "rb");
if (file == NULL)
{
res.errno = errno;
return (&res);
}
fseek (file, req->start, SEEK_SET);
bytes = fread(res.readfile_res_u.part.data, 1, 1024, file);
res.readfile_res_u.part.bytes = bytes;
res.readfile_res_u.part.sid = Id;
res.readfile_res_u.part.rid = req->sid;
res.errno = 0;
fclose(file);
//log the transaction
FILE *log = NULL;
log = fopen(fileLog, "a");
fprintf(log,"R,");
for(i=0;i<5;i++)
fprintf(log,"%d,",cur_ts[i]);
fprintf(log,"%d,",req->sid);
fprintf(log,"%s,",req->name);
fprintf(log,"%d\n",req->start);
fclose(log);
return (&res);
}
}
int* send_file_1_svc(partsend *rec, struct svc_req *rqstp)
{
int i;
printf("%d",rec->rid);
if(rec->rid == Id)
{
FILE *file;
int write_bytes;
static int result;
cur_ts[Id]++;
//update the timestamp
for(i=0;i<5;i++)
cur_ts[i] = rec->ts[i];
char fn[3*MAXLEN] = "storage/";
strcat(fn,rec->name);
file = fopen(fn, "a");
if (file == NULL) {
result = errno;
return &result;
}
write_bytes = fwrite(rec->data, 1, rec->bytes, file);
fclose(file);
result = 0;
//log the transaction
FILE *log = NULL;
log = fopen(fileLog, "a");
fprintf(log,"S,");
for(i=0;i<5;i++)
fprintf(log,"%d,",cur_ts[i]);
fprintf(log,"%d,",rec->sid);
fprintf(log,"%s\n",rec->name);
fclose(log);
return &result;
}
}
Here's my client 1 code.
#include <rpc/rpc.h>
#include <stdio.h>
#include <string.h>
#include "maekawa.h"
extern __thread int errno;
int Id = 4;
char fileLog[50] = "client_1_file_log.txt";
int cur_ts[5] = {0};
//Explicit Replication due to lack of Active Directory Service in NFS.
int idMap[4] = {0,2,3,1};
char hostMap[4][MAXLEN] = {"","localhost","localhost","localhost"};
int get_file(char *host, char *name, int serverno) //just to ensure all servers are not operating on same domain, we use serverno.
{
CLIENT *clnt;
int total_bytes = 0, write_bytes;
readfile_res *result;
request req;
FILE *file;
req.name = name;
req.start = 0;
int i;
req.sid = Id;
req.rid = serverno;
clnt = clnt_create(host, FTPROG, FTVER, "tcp");
if (clnt == NULL)
{
clnt_pcreateerror(host);
exit(1);
}
file = fopen(name, "wb");
FILE *log = NULL;
log = fopen(fileLog, "a");
while (1)
{
cur_ts[Id]++;
for(i=0;i<5;i++)
req.ts[i] = cur_ts[i];
req.start = total_bytes;
result = retrieve_file_1(&req, clnt);
if (result == NULL)
{
clnt_perror(clnt, host);
exit(1);
}
if (result->errno != 0)
{
errno = result->errno;
perror(name);
exit(1);
}
write_bytes = fwrite(result->readfile_res_u.part.data, 1, result->readfile_res_u.part.bytes, file);
total_bytes += result->readfile_res_u.part.bytes;
//log the transaction
fprintf(log,"G,");
for(i=0;i<5;i++)
fprintf(log,"%d,",cur_ts[i]);
fprintf(log,"%d,",req.sid);
fprintf(log,"%s,",req.name);
fprintf(log,"%d\n",req.start);
if (result->readfile_res_u.part.bytes < MAXLEN)
break;
}
fclose(file);
fclose(log);
return 0;
}
int put_file(char *host, char *name, int serverno)//just to ensure all servers are not operating on same domain, we use serverno.
{
CLIENT *clnt;
char data[1024];
int total_bytes = 0, read_bytes;
int *result;
partsend part;
FILE *file;
int i;
part.sid = Id;
part.rid = serverno;
clnt = clnt_create(host, FTPROG, FTVER, "tcp");
if (clnt == NULL)
{
clnt_pcreateerror(host);
exit(1);
}
file = fopen(name, "r");
part.name = name;
FILE *log = NULL;
log = fopen(fileLog, "a");
for(i=0;i<5;i++)
part.ts[i] = cur_ts[i];
while (1)
{
part.bytes = total_bytes;
read_bytes = fread(part.data, 1, MAXLEN, file);
total_bytes += read_bytes;
part.bytes = read_bytes;
result = send_file_1(&part, clnt);
if (result == NULL)
{
clnt_perror(clnt, host);
exit(1);
}
if (*result != 0)
{
errno = *result;
perror(name);
exit(1);
}
for(i=0;i<5;i++)
cur_ts[i] = part.ts[i];
//log the transaction
fprintf(log,"P,");
for(i=0;i<5;i++)
fprintf(log,"%d,",cur_ts[i]);
fprintf(log,"%d,",part.sid);
fprintf(log,"%s,",part.name);
fprintf(log,"%d\n",part.bytes);
if (read_bytes < MAXLEN)
break;
}
fclose(file);
fclose(log);
return 0;
}
int read_command(char *host)
{
char command[MAXLEN], filepath[MAXLEN];
int serverno;
printf("> ");
fflush(stdin);
scanf("%s",command);
if(strcmp(command, "exit") == 0)
{
exit(0);
}
scanf(" %s %d",filepath,&serverno);
if(serverno<=0 || serverno>=4)
{
printf("Choose a server number in [1,2,3].");
}
else
{
if (strcmp(command, "get") == 0)
{
return get_file(host,filepath,serverno);
}
else if(strcmp(command, "put") == 0)
{
int updateResult,replicationResult=-1;
updateResult = put_file(host,filepath,serverno);
/*if(updateResult == 0)
{
//explicit Replication
replicationResult = put_file(hostMap[serverno],filepath,idMap[serverno]);
}
else if(replicationResult != 0)
{
printf("Replication failed.");
}*/
return 0;
}
else
{
return -1;
}
}
}
int main(int argc, char *argv[])
{
int result;
if (argc != 2)
{
fprintf(stderr, "usage: %s host\n", argv[0]);
exit(1);
}
while(TRUE)
{
result = read_command(argv[1]);
}
return 0;
}
I am trying to use Maekawa algorithm to implement file replication explicitly through my client. However, it's being ridiculously impossible to run multiple servers on RPC on same localhost. Is it even possible? If I run the code on different computers, would that work?
Currently I am receiving segmentation fault from the server that is run after the first server. The client just blurts out Connection reset by peer. Is there anyway I can make this work?
I'm a newbie with recursion. How do I fopen and fclose a file in a recursive function?
void make(LINK lis, char *name, int flag, FILE *f)
{
if (lis == NULL) {
fclose(f);
}
else {
if (flag == 0) {
FILE *f = fopen(name, "w");
flag = 1;
}
else {
fprintf(f, "CODICE: %d\n", lis->d.codice);
make(lis->next, name, 1, f);
}
}
}
My goal is to recursively write "codice" --> CODE in a file.
Your most immediate problem is that on the first call, you open the file and then return to the main program, without processing anything. Opening the file should be a simple test, not an if-then-else.
void make(LINK lis, char *name, FILE *f)
{
if (!lis) {
fclose(f);
}
else {
if (f) {
f = fopen(name, "w");
}
fprintf(f, "CODICE: %d\n", lis->d.codice);
make(lis->next, name, f);
}
}
}
How do I fopen and fclose a file in a recursive function?
Be sure to do so at the same level of recursion.
Consider first how the nth and first would look separately:
void make_nth(LINK lis, FILE *outf) {
if (lis) {
fprintf(outf, "CODICE: %d\n", lis->d.codice);
make_nth(lis->next, outf);
}
}
void make_1st(LINK lis, const char *name) {
FILE *f = fopen(name, "w");
if (f) {
make_nth(lis, f);
fclose(f);
}
}
// Usage
LINK lis = ...;
make_1st(lis, codice.txt);
Now put that together. Various ways exist to do this.
void make(LINK lis, const char *name, FILE *outf) {
if (name) {
assert(outf == NULL);
FILE *f = fopen(name, "w");
if (f) {
make(lis, NULL, f);
fclose(f);
}
} else {
if (lis) {
fprintf(outf, "CODICE: %d\n", lis->d.codice);
make(lis->next, NULL, outf);
}
}
}
// Usage
LINK lis = ...;
make(lis, codice.txt, NULL);
My program compares two text files and puts the differences in file one in a third text file. However, when my file one's size is larger than my file two's size a 'ÿ' character is placed at the end of the third file. For example suppose file one consists of "I like pickles." and file two consists of "I like dogs." then the third file will consist of "pickles.ÿ". Is there a way to get rid of this? And why is this happening? Here is my program:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int ch1, ch2;
int size1, size2;
FILE *fh1, *fh2, *diffone=stdout;
if( argc<3 ) {
printf("need two file names\n"); return(1);
}
if(!(fh1 = fopen(argv[1], "r"))) {
printf("cannot open %s\n",argv[1]); return(2);
}
if(!(fh2 = fopen(argv[2], "r"))) {
printf("cannot open %s\n",argv[2]); return(3);
}
if(argc>3) {
if(!(diffone = fopen(argv[3], "w+"))) {
printf("cannot open %s\n",argv[3]); return(4);
}
}
fseek(fh1, 0, SEEK_END);
size1 = ftell(fh1);//gets size of fh1
fseek(fh1, 0, SEEK_SET);
fseek(fh2, 0, SEEK_END);
size2 = ftell(fh2);//gets size of fh2
fseek(fh2, 0, SEEK_SET);
while((!feof(fh1)) || (!feof(fh2)))
{
ch1=ch2='-';
if(!feof(fh1)) ch1 = getc(fh1);
if(!feof(fh2)) ch2 = getc(fh2);
if (size2 > size1)
{
if(ch1 != ch2 && (!feof(fh1)))
{
fprintf(diffone,"%c", ch1);
}
}
else
{
if (ch1 != ch2)
{
fprintf(diffone,"%c", ch1);
}
}
}
}
feof() only returns true after fgetc() has returned EOF (-1).
See Why is “while ( !feof (file) )” always wrong?
You are not doing any error checking on fgetc(), and you are not checking for EOF on fh2 when size1 > size2.
Try this instead:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int ch1, ch2;
int eof1 = 0, eof2 = 0;
FILE *fh1, *fh2, *diffone=stdout;
if (argc < 3) {
printf("need two file names\n");
return(1);
}
if (!(fh1 = fopen(argv[1], "r"))) {
printf("cannot open %s\n",argv[1]);
return(2);
}
if (!(fh2 = fopen(argv[2], "r"))) {
printf("cannot open %s\n",argv[2]);
return(3);
}
if (argc > 3) {
if (!(diffone = fopen(argv[3], "w+"))) {
printf("cannot open %s\n",argv[3]);
return(4);
}
}
while(1)
{
if (!eof1) {
ch1 = fgetc(fh1);
if (ch1 == EOF) {
if (ferror(fh1)) {
printf("cannot read from %s\n",argv[1]);
return(5);
}
eof1 = 1;
}
}
else {
ch1 = '-';
}
if (!eof2) {
ch2 = fgetc(fh2);
if (ch2 == EOF) {
if (ferror(fh2)) {
printf("cannot read from %s\n",argv[2]);
return(6);
}
eof2 = 1;
}
}
else {
ch2 = '-';
}
if ((eof1) && (eof2))
break;
if ((ch1 != ch2) || (eof1 != eof2)) {
if (fputc(ch1, diffone) == EOF) {
if (argc > 3) {
printf("cannot write to %s\n",argv[3]);
}
return(7);
}
}
}
return 0;
}
Check EOF after each fgetc().
Avoid using feof(). Recall feof() becomes true after an EOF was first returned from a read.
Instead of
while((!feof(fh1)) || (!feof(fh2))) {
if(!feof(fh1)) ch1 = getc(fh1);
if(!feof(fh2)) ch2 = getc(fh2);
Use
while (1) {
ch1 = fget(fh1);
ch2 = fget(fh2);
if (ch1 == EOF) {
if (ch2 == EOF) break;
ch1 = '-';
}
if (ch2 == EOF) {
ch2 = '-';
}
....
}
This problem occurs when you are trying to fetch from file first and then print
for example-
ch=fgetc(fp2);
while(ch!=EOF)
{
ch = fgetc(fp2);
fputc(ch, fp1);
}
INSTEAD DO-
ch=fgetc(fp2);
while(ch!=EOF)
{
fputc(ch, fp1);
ch = fgetc(fp2);
}