C - reading a file and appending data to another - c

I am trying to open a file (that wants to be a small archive) and I want to copy another file content in it. The code is the following:
FILE * arch;
FILE * par;
void read_words (FILE *f)
{
char x[1024];
while (fscanf(f," %s",x)==1)
{
fprintf(arch," %s", x);
}
}
int main(int argc, char * argv[])
{
char * nome;
nome = argv[1];
archivio = scrivi(getcwd(NULL, 0), nome);
arch = fopen(archivio, "w+");
par = fopen(argv[2], "r+");
read_words(par);
return 0;
}
Please assume that "archivio" is a working path.
i call the function as follows: ./a.out archiveName FilePath.
All i want to do is opening this archive, then, after some fprintfs (that work correctly, not shown here) opening another file and write its content in archive.
The problem is in the function read_words. It works if taken alone (I took code from here), but if I insert that here, it doesn't work, because it doesn't even enter in while (fscanf(f," %s",x)==1). In fact archive file is always empty.
Can you help me find out why?
Thanks
PS: This is an example text i tried to insert:
La funzione mkbkp si occupa della creazione di un archivio contenente i file e le cartelle passate come parametri.
The strange thing is that if you make a c file with only read_words, it works fine.

Given the way you describe the behavior of your program, I can only suppose that you are not reading the file that you want to be reading. Try using this function:
void show_file (const char *filename, FILE *out) {
int c;
FILE *file;
fprintf(out, "%s(%s) BEGIN\n", __func__, filename);
file = fopen(filename, "r");
if (file) {
while ((c = fgetc(file)) != EOF) {
fputc(c, out);
}
fclose(file);
} else {
fprintf(out, "%s: failed to open file '%s' (%d)\n", __func__, filename, errno);
}
fprintf(out, "%s(%s) END\n", __func__, filename);
}
You can call this function from your main like this:
show_file(argv[2], stderr);
Make sure the path to the file and the contents of the file match your expectations.

Related

How to dump txt file in C?

#include <stdio.h>
int main(void) {
int name;
int arrival_time;
int size;
int ret;
FILE * fp = fopen_s("C:\\NIA\\data.txt", "rt");
while (1)
{
ret = fscanf_s(fp, "%d %d %d", &name, &arrival_time, &size);
if (ret == EOF)
break;
printf("%d %d %d \n", name, arrival_time, size);
}
return 0;
}
I want to dump my txt file to project but errors are coming out. I'm confused about memory initiation and file format, variables, etc. How can I fix this and print values well?
My txt file is :
Your question lacks the most important information: What is going wrong.
When I compile your code, I get errors for fopen_s. (OK, this is mainly because I use gcc ;) )
The manual tells us how this function looks like:
errno_t fopen_s(
FILE** pFile,
const char *filename,
const char *mode
);
This means, you must use it like this:
errno_t err;
FILE *fp;
err = fopen_s(&fp, "C:\\NIA\\data.txt", "rt");
if (err != 0)
{
fprintf(stderr, "The file was not opened\n" );
exit(1);
}
Or you stick to standard functions and use them as you already tried:
FILE *fp;
fp = fopen("C:\\NIA\\data.txt", "rt");
if (fp = NULL)
{
fprintf(stderr, "The file was not opened\n" );
exit(1);
}
You should definitely add checks for all return values. At least for I/O related functions like fopen and scanf.
Also closing your file would be adviseable. While it is only opened in read mode, it will not cause much trouble as it is closed automatically on program termination, but it is surely good style to do it.
An improved version could look like this:
(As you do not scan strings, there is no benefit using MS non-standard function scanf_s)
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int name;
int arrival_time;
int size;
FILE * fp = fopen("data.txt", "rt");
if (fp == NULL) {
perror("File data.txt cannot be opened");
exit(1);
}
while (fscanf(fp, "%d %d %d", &name, &arrival_time, &size) == 3)
{
printf("%d %d %d\n", name, arrival_time, size);
}
fclose(fp);
return 0;
}
This prints the content of your data.txt file on the console.
If dumping you txt file means closing the txt file after using it, you can use the following
fclose(fp);
before the return 0;

How to write data to multiple files using arrays of pointers of file in C?

This is my code which I have written so far
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
char quit[4] = "exit";
// char *filearray[100];
char filearray[100][14];
FILE **originalfilearray;
int counter = 0;
//Copy part
while(1){
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
break;
printf("Cannot open file %s \n", filename);
exit(0);
}
strcpy(filearray[counter], filename);
originalfilearray[counter] = fptr1;
counter+=1;
}
//Paste part
for (int i = 0; i < counter; i++)
{
printf("Enter the filename to open for writing for file %s\n", filearray[i]);
scanf("%s", filename);
fptr2 = fopen(filename, "w");
// Read contents from file
c = fgetc(fptr2);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(originalfilearray[i]);
}
printf("\nContents copied to %s\n", filename);
}
}
The problem occurs when I run the paste code the file is created but no content is pasted.
I have already tried reading many post regarding array of pointers of file. Some suggested to create originalfilearray variable with a single pointer some with double.
The major problem I guess is with the copy part.
Can someone please help me with the part where I need to copy the data of multiple files in the originalfilearray variable
Thank You
Apart from not allocating memory for originalfilearray, which other user explained, here are some things you are doing wrong
In
c = fgetc(fptr2);
You are trying to get character from an empty file you just opened in
fptr2 = fopen(filename, "w");
what you should be doing is starting a file pointer fptr and opening
FILE *fptr=fopen(filearray[i], "r");
and then copying content into it with
while ((c = fgetc(fptr))!= EOF)
{
fputc(c, fptr2);
}

Why does fgets continuousely return NULL?

I'm trying to write a program that can open all given files in a directory, and output the files with some changes to another directory given a path specified by the user. I made a function that will be called after fork() for each filename encountered in the current directory, and the output will have the same name in this new directory. I have looked all over, and I still can't find a reason as to why fgets() keeps returning NULL.
void sorter(char *fileName, char *directory, char* newName){
FILE *edit = fopen(fileName, "r");
char buf[700];
char *bufp = buf;
char *fLine = fgets(bufp, sizeof(buf), edit);
if (edit == NULL){
exit(EXIT_FAILURE);
}
printf("%s\n", fLine);
chdir(directory);
FILE *output=fopen(newName, "w");
while(fLine){
fprintf(output, fLine);
fprintf(output, "done");
}
fclose(output);
fclose(edit);
}

Writing file name dinamically through the code - C

I'm making a program that basically receives 2 files (a .pal and a .dic file) and outputs a file called solution file (blabla.sol). However that solution file's name depends on one of those files that the program received. How can I modify my program in order to change the output file's name depending on the name of the received file's name? In this case I want it to be the same names as my name_pal file.
Here's the program that I've already written (right now, as it is, it only outputs a file with a fixed name):
int main(int argc, char *argv[])
{
char name_dic[MAX_FILENAME_SIZE];
char name_pal[MAX_FILENAME_SIZE];
char name_sol[] = "prob0.sol";
char words_dic[MAX_WORD_SIZE];
char words_pal[MAX_WORD_SIZE];
char word_same_size[MAX_WORD_SIZE];
char dic_total[MAX_DIC_SIZE][MAX_WORD_SIZE];
char pal_total[MAX_PAL_SIZE][MAX_WORD_SIZE];
FILE *dic, *pal, *sol;
if (argc < 3)
{
printf("Missing files.\n");
exit(1);
}
strcpy(name_dic, argv[1]);
strcpy(name_pal, argv[2]);
dic = fopen(name_dic, "r");
if (dic == NULL)
{
printf("Can not open dictionary file: %s\n", name_dic);
exit(1);
}
pal = fopen(name_pal, "r");
if (pal == NULL)
{
printf("Can not open problem file: %s\n", name_pal);
exit(1);
}
sol = fopen(name_sol, "w");
if (sol == NULL)
{
printf("Can not open solution file: %s\n", name_sol);
exit(1);
}
/* rest of the code */
You can write a truncate function at the '.' and then append sol as shown in snippet below.
char name_sol[MAX_FILENAME_SIZE];
int i;
for(i=0;i<MAX_FILENAME_SIZE;i++){
name_sol[i]=name_pal[i];
if(name_sol[i]=='.') break;
}
strcpy(name_sol+i+1,"sol");
printf("%s\n",name_sol);

Characters missing when writing in file in C

I've searched all I could and I'm actually not sure how to look for an answer as it's pretty specific.
I have a function that checks if a file exists and if it doesn't, create it and writes some parameters in it. After that another function adds some data in the file. But the first line of data is missing the number of characters that are in the line created with the file.
The code looks like this (I'm only putting the parts I think are relevant, as it's pretty messy) :
the function that checks if the file exists is :
int check_datafile(char *fname, Par *par){
char filename[64] = "data/";
strcat(filename, fname);
FILE* fdesc = NULL;
fdesc = fopen(filename, "r");
if (fdesc == NULL){
fdesc = fopen(filename, "w");
fprintf(fdesc,"%d %.3f \n", par -> L, par -> t);
close(fdesc);
}
return 1;
}
Then the function that writes is :
void result_block(Par *par, double M, double M2, double M4, int ntot, char *fname)
{
char filename[64] = "data/";
strcat(filename, fname);
FILE* fichier = NULL;
fichier = fopen(filename, "a");
if (fichier != NULL) // File should already exist
{
fprintf(fichier, "%.3f %.3f %.3f\n", M/ntot, M2/ntot, M4/ntot);
fclose(fichier);
}
else
{
printf("Problem with the file : %s\n", filename);
exit(0);
}
}
They are called by
int initialize_mc(Par *par, int *spin) {
int i, L2 = par->L * par->L;
double T = par -> t;
char *f2;
double ex[1];
ex[0] = exp(-2/T);
if (!par->L) {
printf("Give system size N!\n");
return 0;
}
init_ran(par->seed);
sprintf(fname, "%3.3d_%5.3f", par->L, par->t);
check_datafile(fname, par);
mc(par, spin, ex);
return 1;
}
And the function result_block is called in the function mc.
Typically, I want the file to look like this :
16 2.210
205.412 43371.160 2010463301.344
201.876 42319.600 1951381846.720
198.396 40897.632 1836904396.032
197.652 40743.856 1833699088.000
...
And it looks like this :
16 2.210
371.160 2010463301.344
201.876 42319.600 1951381846.720
198.396 40897.632 1836904396.032
197.652 40743.856 1833699088.000
...
The the first line of data is cut by the same amount of characters that is in the first line of the file.
What can cause this problem?
close(fdesc); needs to be fclose(fdesc);. When you use FILE * you are implicitly using a buffer on your output. You need to call fclose so that the buffer gets flushed.
By calling close you are actually casting your pointer to an int and closing some random file descriptor (which presumably fails most of the time). You're not closing the FILE * at all.

Resources