fprintf issues in RPC C program - c

I'm having issues with fprintf in my RPC program. It opens a file but won't read the content into a file. It will print the content using printf but fprint leaves the file blank. How do I fix this issue? Thank you
#include <rpc/rpc.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include"lab5.h"
char * filename(char *str)
{
file = str;
printf("filename = %s\n",file);
return file;
}
int writefile(char *content)
{
FILE *fp1;
fp1 = fopen("recfile.txt", "w");
if(fp1 == NULL)
{
printf("File can't be created\n");
return 0;
}
printf("%s\n",content);
int i = fprintf(fp1, "%s", content);
printf("i = %d\n",i);
close(fp1);
return 1;
}
int findwordcount(char* searchword)
{
char *grep;
int count;
int status;
FILE *fp;
grep = (char*)calloc(150, sizeof(char));
strcpy(grep, "grep -c \"");
strcat(grep, searchword);
strcat(grep, "\" ");
strcat(grep, "recfile.txt");
strcat(grep, " > wordcount.txt");
status = system(grep);
printf("status = %d\n", status);
if(status != 0)
{
count = 0;
}
else
{
fp = fopen("wordcount.txt", "r");
fscanf(fp, "%d", &count);
printf("count = %d\n", count);
}
return count;
}

In your function int writefile (char *content); you are currently using close(fp1);. Instead to close the file, you should fclose(fp1) instead.

Related

Load string containing words from file

I need to load strings from file into a struct array.
CORRECT OUTPUT:
4
Sarajevo,345123
Tuzla,123456
Mostar,101010
Banja Luka,234987
MY OUTPUT:
1
Sarajevo 345123
Tuzla 123456
Mostar 101010
Banja Luka 234987,544366964
Code:
#include <stdio.h>
#include <string.h>
struct City {
char name[31];
int number_of_citizen;
};
int load(struct City cities[100], int n) {
FILE *fp = fopen("cities.txt", "r");
int i = 0;
while (fscanf(fp, "%[^,]s %d\n", cities[i].name, &cities[i].number_of_citizen)) {
i++;
if (i == n)break;
if (feof(fp))break;
}
fclose(fp);
return i;
}
int main() {
int i, number_of_cities;
struct City cities[10];
FILE* fp = fopen("cities.txt", "w");
fputs("Sarajevo 345123", fp); fputc(10, fp);
fputs("Tuzla 123456", fp); fputc(10, fp);
fputs("Mostar 101010", fp); fputc(10, fp);
fputs("Banja Luka 234987", fp);
fclose(fp);
number_of_cities = load(cities, 10);
printf("%d\n", number_of_cities);
for (i = 0; i < number_of_cities; i++)
printf("%s,%d\n", cities[i].name, cities[i].number_of_citizen);
return 0;
}
Could you explain me how to fix this? Why my program only loaded 1 city?
The fscanf() conversion string is incorrect: instead of "%[^,]s %d\n" you should use:
while (i < n && fscanf(fp, "%30[^,],%d",
cities[i].name,
&cities[i].number_of_citizen) == 2) {
i++;
}
Or better:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int load(struct City cities[], int n) {
char buf[200];
int i = 0;
char ch[2];
FILE *fp = fopen("cities.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", "cities.txt",
strerror(errno));
return -1;
}
while (i < n && fgets(buf, sizeof buf, fp)) {
if (sscanf(buf, "%30[^,],%d%1[\n]",
cities[i].name,
&cities[i].number_of_citizen, ch) == 3) {
i++;
} else {
fprintf(stderr, "invalid record: %s\n", buf);
}
}
fclose(fp);
return i;
}
Also change your main function to output commas between the city names and population counts:
int main() {
int i, number_of_cities;
struct City cities[10];
FILE *fp = fopen("cities.txt", "w");
if (fp) {
fputs("Sarajevo,345123\n", fp);
fputs("Tuzla,123456\n", fp);
fputs("Mostar,101010\n", fp);
fputs("Banja Luka,234987\n", fp);
fclose(fp);
}
number_of_cities = load(cities, 10);
printf("%d\n", number_of_cities);
for (i = 0; i < number_of_cities; i++)
printf("%s,%d\n", cities[i].name, cities[i].number_of_citizen);
return 0;
}
EDIT: since there are no commas in the database file, you must use a different parsing approach:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int load(struct City cities[], int n) {
char buf[200];
int i = 0;
FILE *fp = fopen("cities.txt", "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", "cities.txt",
strerror(errno));
return -1;
}
while (i < n && fgets(buf, sizeof buf, fp)) {
/* locate the last space */
char *p = strrchr(buf, ' ');
if (p != NULL) {
/* convert it to a comma */
*p = ',';
/* convert the modified line */
if (sscanf(buf, "%30[^,],%d",
cities[i].name,
&cities[i].number_of_citizen) == 2) {
i++;
continue;
}
}
fprintf(stderr, "invalid record: %s", buf);
}
fclose(fp);
return i;
}

Trying to read from a file that I know exists and is good but will not open

When I try to open a file "canbus.txt.txt" it is coming back with an error message that reads out "error: No error" repeatedly. I cannot find where this issue would be coming from. My file is in the main project directory and the name and extensions are all correct.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int i;
char value;
char test[60];
char *line;
int num = 0;
int address[25];
int values[25];
void ms_delay (int N)
{
T1CON = 0x08030;
int delay = N * 62.5; // 1 Milisecond => .001 / (256 * (1/16,000,000)) = 62.5
TMR1 = 0;
while (TMR1 < delay);
}
int main (void)
{
PIN_MANAGER_Initialize();
UART1_Initialize();
ECAN1_Initialize();
ECAN1_ReceiveEnable();
INTERRUPT_Initialize();
FILE *fp;
char* filename = "canbus.txt.txt";
fp = fopen(filename, "r");
if(fp == NULL){
perror("Error");
exit(EXIT_FAILURE);
}
while(fgets(line, sizeof(line), fp)){
fscanf(fp, "%lf %lf", &address[num], &values[num]);
sprintf(test, "Value = %lf Other = %lf", address[num], values[num]);
int i = 0;
while(test[i] != '\0'){
UART1_Write(test[i]);
i++;
}
++num;
}
ms_delay(250);
UART1_Write(0x0D);
UART1_Write(0x0A);
fclose(fp);
return 0;
}
#include <stdio.h>
int main()
{
FILE *fr;
char c;
fr = fopen("prog.txt", "r");
while( c != EOF)
{
c = fgetc(fr); /* read from file*/
printf("%c",c); /* display on screen*/
}
fclose(fr);
return 0;
}
To know more https://www.codesdope.com/c-enjoy-with-files/

Better way to convert string to integer

I wrote this code to read a variable in a .txt file, ignore the first character and convert into a integer.It works but looks dumb, is there a better way to do this? I'm using just one string here but it's supposed to work with four.
void read(char a[])
{
int i;
char a1[3];
for (i = 0; i<3; ++i){
a1[i]= a[i+1];
}
int b1 = atoi(a1);
}
int main()
{
FILE *file;
file = fopen( "file.txt", "r");
if (file == NULL) {
printf( "Arquivo nao encontrado\n");
}
char a[4];
fscanf(file, "%s\n",&a);
read(a);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char filename[] = "file.txt";
FILE *fp = fopen(filename, "r");
if (fp == 0)
{
fprintf(stderr, "Failed to open file %s for reading\n", filename);
return(EXIT_FAILURE);
}
int value;
if (fscanf(fp, "%*c%d", &value) != 1)
{
fprintf(stderr, "Failed to read integer value from file %s\n", filename);
fclose(fp);
return EXIT_FAILURE;
}
printf("Read %d\n", value);
fclose(fp);
return 0;
}
The %*c reads a single character but does not assign it. The * to suppress an assignment is a general mechanism in the scanf()
family of functions.
Untested code.

Unable to read a file and pass into arguments

1) I'm trying to open a file, read the mix data (ints, chars and strings) and store them into args.
1.1) so in the sample.txt is a total of 13 (excluding args[0])
2) Need to read a file from terminal "./myprog.c < sample.txt"
Heres my code and have no idea where i went wrong:
sample.txt:
123 213 110 90 1
hello my friend
boo bleh
a b c
myprog.c:
#include <stdio.h>
int main()
{
int i = 1;
FILE *fstin=fopen(argv[0], "r"); //open the file
if (fstin == NULL) {
puts("Couldn't fopen...");
return -1;
}
//Getting all the inputs from file
while ((fscanf(fstin, "%d", argv[i])) != EOF){
i++;
}
fclose(fstin);
for (i=0; i<10; i++) {
printf("%d\n",argv[i]);
}
return 0;
}
Any help is greatly appreciated!
PS: Would like if anyone could post their complete solution? Will upload unto this post and let everyone have a review of this problem
PPS: Please excuse the poor level of coding as I am a beginner and completely new to C.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int ac, char *av[]){
int i, argc=0;
char **argv=NULL, data[16];
FILE *fstin = stdin;
if(ac == 2){
if(NULL==(fstin = fopen(av[1], "r"))){
puts("Couldn't fopen...");
return -1;
}
}
while (1==fscanf(fstin, "%15s", data)){
argv = realloc(argv, (argc+1)*sizeof(char*));
argv[argc] = malloc(strlen(data)+1);
strcpy(argv[argc++], data);
}
if(ac == 2)
fclose(fstin);
for (i=0; i<argc; ++i) {
printf("%s\n", argv[i]);
}
//deallocate
return 0;
}
You are making mistake at 2nd point where you divert your file to other file which is wrong. Actually you need to first compile and need to make executable.
gcc -o my_prog ./myprog.c -Wall
You need to execute this program as below to read file from c program:
./my_prog ./sample.txt
As you are new to C programming first go to man pages related to file operations.
Solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
//If command line argument is not inserted then stop operation
if (2 != argc) {
printf("Invalid number of arguments : %d\n", argc);
return -1;
}
int size = 0, ret = 0;
char *data = NULL;
FILE *fp = NULL;
//Open file in read mode given from command line argument
if (NULL != (fp = fopen(argv[1], "r")))
{
//Find size of file
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
//if file is empty no need to read it.
if (size > 0)
{
//Data pointer which contains file information
data = (char *) calloc(sizeof(char), size);
if (NULL != data)
{
//Read whole file in one statement
fread(data, sizeof(char), size, fp);
printf("File %s is readed successfully\n", argv[1]);
printf("Data:\n");
printf("%s\n", data);
free(data); data = NULL;
}
else
{
perror("memory allocation failed\n");
ret = -1;
}
}
else
{
printf("File %s is empty\n", argv[1]);
}
fclose(fp); fp = NULL;
}
else
{
perror("File open failed\n");
ret = -1;
}
return ret;
}
Now Test it on your setup and if any query please post comments.

c, 2d char array and fopen

I'm trying to make a program that reads a file with list of names. The number of those names can vary, as well as the names lengths. I want to store them in an array of arrays of char, and read each row as a string to later open the file that corresponds to the name in question. But when I try to open the first one, I have an error opening file.
I'm totally out of ideas.
Help, please?
Here is the code relevant to this action:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int glimps(char *fname);
int write_av(char *fname, int NumbFiles);
int clr(char *fname);
int readFile(char *fname, int i);
double *dalpha, *alpha, *Ln_t, *LnLnA, Conc;
long *time, *weights, *Lmax, Nmax;
char *av_file, **in_files, *antetka;
/****************************************************************************/
int main(int argc, char *farg[])
{
int i, NumbFiles, flag;
long row;
char *a1;
FILE *fp;
av_file = farg[1];
printf("av_file = %s\n",av_file);
NumbFiles = glimps(av_file);
in_files = (char **) malloc (sizeof(char *) * NumbFiles);
for (i=0 ; i<NumbFiles ; i++)
in_files[i] = (char *) malloc (sizeof(char) * 200);
Lmax = (long *) calloc((size_t) NumbFiles, sizeof(long));
if((in_files == NULL)||(Lmax==NULL)) printf("Грешка при read алок.\n, "), exit(-1);
if (flag = readFile(av_file, -1))
printf("Error in read av_file %s\n", av_file), exit(-1);
weights = (long *) calloc((size_t) Nmax, sizeof(long));
for(i = 0; i<Nmax; i++) weights = 0;
for(i = 0; i<NumbFiles; i++)
{
//if (flag = readFile(&(*in_files[i]), i))
if (flag = readFile(in_files[i], i))
printf("Error in in_files[%d], %s\n",i, &(*in_files[i])), exit(-1);
}
if (flag = write_av(av_file, NumbFiles))
printf("Error in write_av(%s)\n,", av_file), exit(-1);
exit(0);
}
/****************************************************************************/
int glimps(char *fname)
{
FILE *fp;
char buf[140];
int cnt=0;
fp = fopen (fname, "r");
while (fgets(buf,140,fp) )
{
cnt++;
}
fclose(fp);
return (cnt);
}
/****************************************************************************/
int readFile(char *fname, int k)
{
int cnt=0;
FILE *fp;
char buf[200], dummy[13];
printf("fname is %s\n", fname); getchar();
fp = fopen (fname, "r");
if(fp==(NULL)) return(-1);
if(!strcmp(fname,av_file) )
{
while (fgets(in_files[cnt++],200,fp) );
}
else
{
printf("read TUK!\n"); getchar();
fgets(buf,200,fp);
sscanf(buf,"%s %s %s %s %s %s %s %ld %s %s %lf\n",
dummy, dummy,dummy,dummy,dummy,dummy,dummy, &Lmax[k],
dummy, dummy, &Conc);
fgets(buf,200,fp);
sscanf(buf,"%s\n", antetka);
printf("read TUK!\n"); getchar();
while (fgets(buf,200,fp))
{
sscanf(buf,"%ld %lf %lf %s %lf %lf\n",
&time[cnt], &dalpha[cnt], &alpha[cnt], dummy, &Ln_t[cnt],
&LnLnA[cnt]);
weights[cnt++]++;
}
}
fclose(fp);
return (0);
}
...
Console Output:
> ./avr alpha_cubeL.C0.010
av_file = alpha_cubeL.C0.010
fname is alpha_cubeL.C0.010
fname is alpha_cubeL100C0.010
Error in read in_files[0], alpha_cubeL100C0.010
> ls alpha_cubeL100C0.010
alpha_cubeL100C0.010
What happens is that in the readFile function, you read the main file given as argument to make (from the content) several file names in in_files[i], but fgets reads lines including the CR or CRLF (ie the end of line character(s)). Thus later in the program, readFile fails as it tries to open filename + CR [LF].
You may just add a trim function near the top of your program, like
void trim(char *s) {
int i,l = strlen(s);
for (i=l-1 ; i>=0 && (s[i]==10 || s[i]==13) ; i--) s[i] = 0;
}
that removes CR and/or LF that end a string s, and then change the readFile function to trim the file names read in each line, like
while (fgets(in_files[cnt++],200,fp) ) {
trim(in_files[cnt-1]); // cnt-1, or do the cnt++ here (and not above...)
}
Then the files can be opened...
(this is probably not the only problem in this program, but this is a good start)

Resources