I have this function in a code that im trying to enter to an I/O file and I cannot seem to do it.
void show_list(int whyeven[stuff], char *hatred[stuff])
{
for (int g = 0; g < stuff - 1; g++)
{
if (whyeven[g] < 10 || whyeven[g] == 0)
{
printf("%s - %d (*) you should buy more of this stuff\n\n",hatred[g], whyeven[g]);
}
else if (whyeven[g] > 10)
{
printf("%s - %d\n\n", hatred[g], whyeven[g]);
}
}
}
int main()
{
show_list(moarstuff, items);
return 0;
}
printf() prints to stdout. You need to fopen() that file and then use fprintf() with the returned from fopen() FILE* pointer as the first argument.
/* Open the file for writing */
FILE* fp = fopen("filename.txt", "w");
/* Check for errors */
if (fp == NULL)
{
/* Notify the user of the respective error and exit */
fprintf(stderr, "%s\n", strerror(errno));
exit(1);
}
/* Write to the file */
fprintf(fp, "Hello!\n");
/* Close the file */
fclose(fp);
Note: Your question was quite unclear and this answer is based on what I could understand out of it.
Related
I'm trying to print all content of my file but I'm unable to print that to the filebut just first line is being printed, Suggest some way for the same.
First it was just printing 1 line when I hadn't used while loop
When I used while loop with !EOF condition then it didn't even get into while loop and thus was not printing any content.
static void
processNode(xmlTextReaderPtr reader) {
const xmlChar *name, *value;
FILE *fp = fopen("telemetryOutput.txt", "w+");
name = xmlTextReaderConstName(reader);
if (name == NULL)
name = BAD_CAST "--";
value = xmlTextReaderConstValue(reader);
fprintf(fp, "%s\n", "Testing");
// facing issue in this portion:
fprintf(fp, "%d %d %s %d %d",
xmlTextReaderDepth(reader),
xmlTextReaderNodeType(reader),
name,
xmlTextReaderIsEmptyElement(reader),
xmlTextReaderHasValue(reader));
/////
if (value == NULL)
fprintf(fp, "\n");
else {
if (xmlStrlen(value) > 40)
fprintf(fp, " %.40s...\n", value);
else
fprintf(fp, " %s\n", value);
}
}
/**
* streamFile:
* #filename: the file name to parse
*
* Parse and print information about an XML file.
*/
static void
streamFile(const char *filename) {
xmlTextReaderPtr reader;
int ret;
reader = xmlReaderForFile(filename, NULL, 0);
if (reader != NULL) {
ret = xmlTextReaderRead(reader);
while (ret == 1) {
processNode(reader);
ret = xmlTextReaderRead(reader);
}
xmlFreeTextReader(reader);
if (ret != 0) {
fprintf(stderr, "%s : failed to parse\n", filename);
}
} else {
fprintf(stderr, "Unable to open %s\n", filename);
}
}
int main(int argc, char **argv) {
if (argc != 2)
return(1);
/*
* For creating file
*/
FILE *fptr = fopen("telemetryOutput.txt", "rb+");
char there_was_error = 0;
char opened_in_read = 1;
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("telemetryOutput.txt", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
/*
* this initialize the library and check potential ABI mismatches
* between the version it was compiled for and the actual shared
* library used.
*/
LIBXML_TEST_VERSION
streamFile(argv[1]);
/*
* Cleanup function for the XML library.
*/
xmlCleanupParser();
/*
* this is to debug memory for regression tests
*/
xmlMemoryDump();
// File Handling
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
return(0);
}
#else
int main(void) {
fprintf(stderr, "XInclude support not compiled in\n");
exit(1);
}
#endif
I have tried using below method but was unable to get required content
while(!EOF){
fprintf(fp, "%d %d %s %d %d",
xmlTextReaderDepth(reader),
xmlTextReaderNodeType(reader),
name,
xmlTextReaderIsEmptyElement(reader),
xmlTextReaderHasValue(reader));
}
Your logic is wrong. Initially file pointer is at the EOF since the file is empty. Thus it doesn't get into the loop itself.
If you have to print to file only 1 line don't use that condition for while loop.
Also open file in append mode otherwise it might overwrite from start each time you write on it.
I am trying to write a C program to concatenate N files which I should read them from the keyboard and then take all of their concent starting from FILE1 to n and put them on a NEWFILE, my program concatinates all of the N files but the order is not from 1 to n. For example:
I input N=3 and I put three files:
text1.txt (inside the file I have "We cannot")
text2.txt ("live")
text3.txt ("without water.")
and then save the concatination on a finalresult.txt
Now my finalresult.txt should be:
We cannot
live
without water.
But my result is:
withoutwater. We cannot live
Here is my full program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int number;
scanf("%d", &number);
int i;
char a[number][50];
char help[50];
for(i=0; i<number; i++)
{
scanf("%s", help);
strcpy(a[i], help);
}
printf("Concating the content of %d files ...\n", number);
FILE * filer, * filew;
int numr,numw;
char buffer[64];
for(i=0; i<number; i++)
{
filer = fopen(a[i], "rt");
if(filer == NULL)
{
fprintf(stderr, "open read file error.\n");
exit(1);
}
filew = fopen("finalresult.txt","a+t");
if(filew==NULL) {
fprintf(stderr,"open write file error.\n");
exit(1);
}
while(feof(filer)==0) {
numr=fread(buffer,1,100,filer);
if(numr!=100) {
if(ferror(filer)) {
fprintf(stderr,"read file error.\n");
exit(1);
}
}
numw=fwrite(buffer,1,numr,filew);
if(numw!=numr) {
fprintf(stderr,"write file error.\n");
exit(1);
}
}
}
fclose(filer);
fclose(filew);
return 0;
}
You can rewrite this
char a[number][50];
char help[50];
for(i=0; i<number; i++)
{
scanf("%s", help);
strcpy(a[i], help);
}
as
char a[number][50];
for(i=0; i < number; ++i)
scanf("%s", a[i]);
you don't need another intermediate buffer. Also bear in mind, that "%s"
matches only non-empty characters, if your filename has an empty character,
scanf won't read the whole input and leave behind extra characters in the input
buffer, thus messing with the next scanf call. Here it would be better to use
fgets.
char a[number][50];
for(i = 0; i < number; ++i)
{
if(fgets(a[i], sizeof a[i], stdin) == NULL)
{
fprintf(stderr, "Could not read the filename\n");
exit(1);
}
a[i][strcspn(a[i], "\n")] = 0; // removing newline
}
I haven't seen the mode 't' for fopen, is that a an extension of the modes
for Windows?
A problem with your code is that you are calling
filew = fopen("finalresult.txt","a+t");
inside the loop but you never close it inside the loop. FILE* file is buffered,
that means when you use fprintf(file,...) or fwrite(..., file)
the content gets buffered and the content is physically written in the file at a
later point, for example when the buffer is full or you use fflush(filew). So
when you fopen the same file before doing a fflush or fclose, the old
buffered content remains in the buffer and is written at a much later point (in
your case when the program exits), thus overwriting your new content. Your new content
will have the same fate. At the end you end up with a mess because the content
gets overwritten at the end of the program. That's why you see "garbage" in the
file.
So, you have to do fclose before doing fopen with the same filename, or
better you should do the fopen before the loop.
Also this check is incorrect:
if(numr!=100) {
if(ferror(filer)) {
fprintf(stderr,"read file error.\n");
exit(1);
}
}
This would only be correct, if the file size is a multiple of 100. If it's not,
the last block will have less than 100 bytes and you would end your program,
even though the fread had no errors.
So I'd rewrite your program like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(void)
{
size_t num_of_files;
printf("Enter the number of files: ");
fflush(stdout);
if(scanf("%zu", &num_of_files) != 1)
{
fprintf(stderr, "Could not read the number of files\n");
exit(1);
}
int c;
// clearing the input buffer
while((c = getchar()) != '\n' && c != EOF);
char fnames[num_of_files][50];
for(size_t i = 0; i < num_of_files; ++i)
{
printf("Enter the filename %zu: ", i+1);
fflush(stdout);
if(fgets(fnames[i], sizeof fnames[i], stdin) == NULL)
{
fprintf(stderr, "Could not read the filename\n");
exit(1);
}
fnames[i][strcspn(fnames[i], "\n")] = 0; // removing newline
}
FILE *filew = fopen("finalresult.txt", "wt");
if(filew == NULL)
{
fprintf(stderr, "Could not open file finalresult.txt for writing: %s\n",
strerror(errno));
exit(1);
}
for(size_t i = 0; i < num_of_files; ++i)
{
FILE *filer = fopen(fnames[i], "rt");
if(filer == NULL)
{
fprintf(stderr, "could not open %s for reading, skipping: %s\n",
fnames[i], strerror(errno));
continue;
}
char buffer[100];
size_t len;
while((len = fread(buffer, 1, sizeof buffer, filer)) != 0)
{
if(fwrite(buffer, 1, len, filew) != len)
{
fprintf(stderr, "Error writing finalresult.txt\n");
fclose(filer);
fclose(filew);
exit(1);
}
}
if(!feof(filer))
fprintf(stderr, "file %s could not be read completely\n", fnames[i]);
fclose(filer);
}
fclose(filew);
return 0;
}
One of my assignments has the following question:
One function (function #2) of your program is to read in the content of an instance file. To read in
the file "
instance10
001.txt
" you will execute the command:
NameOfProgram -i instance10
001.txt
Here "
-i " is the command-line option that indicates the succeeding argument is the
input filename.
This is what I have done so far, mostly a skeleton:
/* Assignment 1 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])
{
FILE *fp;
int max_x, max_y, num_pt, rand_inst;
int *x_coordinate, *y_coordinate;
int inputfile = 0, outputfile = 0;
int i;
if (argc == 1)
{
/* to generate random instances, accepting parameters from stdin */
printf("Generating random instances...");
printf("Enter the circuit board size MAX_X MAX_Y: ");
scanf("%d %d", &max_x, &max_y);
printf("Enter the number of points NUM_PT: ");
scanf("%d", &num_pt);
printf("Enter the number of random instances to be generated: ");
scanf("%d", &rand_inst);
return 1;
}
for (i = 1; i < argc; i++)
{
if (strcmp (argv[i], "-i") == 0)
inputfile = i+1;
else if (strcmp (argv[i], "-o") == 0)
outputfile = i+1;
}
if (inputfile == 0)
{
/* invalid comman line options */
printf("\nIncorrect command-line\n");
printf("myprogram [-i inputfile [-o outputfile]]");
return -1;
}
**/* THIS IS WHERE I NEED HELP */**
if (inputfile == 1)
{
fp = fopen(/*Name of the input file (instance10_001.txt) */, "r")
}
if ((fp = fopen(argv[inputfile], "r")) == NULL)
{
/* open file error */
return -2;
}
while (fscanf(fp, "%d", &max_x) != 1)
{
if (ferror(fp))
{
/* read error */
fclose(fp);
return -3;
}
if (feof(fp))
{
/* no integer to read */
fclose(fp);
return -4;
}
fscanf(, "%*[^\n]"); /*skip the rest of line */
}
if (fscanf(fp, "%d", &max_y) != 1)
{
/* max_y not following max_x */
fclose(fp);
return -5;
}
while (fscanf(fp, "%d", &num_pt) != 1)
{
if(ferror(fp))
{
/* read error */
fclose(fp);
return -6;
}
if (feof(fp))
{
/* no integer to read */
fclose(fp);
return -7;
}
fscanf(fp, "%*[^\n]"); /* skip the rest of line */
}
x_coordinate = (int *)malloc(num_pt * sizeof(int));
y_coordinate = (int *)malloc(num_pt * sizeof(int));
for (i = 0; i < num_pt; i++)
{
while (fscanf(fp, "%d", &x_coordinate[i]) != 1)
{
if (ferror(fp))
{
/* read error */
fclose(fp);
return -8;
}
if (feof(fp))
{
/* no integer to read */
fclose(fp);
return -9;
}
fscanf(fp, "%*[^\n]"); /* skip the rest of line */
}
if (fscanf(fp, "%d", &y_coordinate[i]) != 1)
{
/* y_coordinate not following x_coordinate */
fclose(fp);
return -10;
}
}
fclose(fp);
if (outputfile > 0)
{
if ((fp = fopen(argv[outputfile], "w")) == NULL)
{
/* open file error */
return -2;
}
fprintf(fp, "##################################################\n");
fprintf(fp, "#%s\n", argv[inputfile]);
fprintf(fp, "#area [0, MAX_X] x [0, MAX_Y]\n");
fprintf(fp, "%d\t%d\n", max_x, max_y);
fprintf(fp, "#number of points NUM_PT\n");
fprintf(fp, "%d\n", num_pt);
fprintf(fp, "#coordinates\n");
for (i = 0; i < num_pt; i++)
{
fprintf(fp, "%d\t%d\n", x_coordinate[i], y_coordinate[i]);
}
fprintf(fp, "#end of instance\n");
fclose(fp);
}
else
{
printf("##################################################\n");
printf("#%s\n", argv[inputfile]);
printf("#area [0, MAX_X] x [0, MAX_Y]\n");
printf("%d\t%d\n", max_x, max_y);
printf("#number of points NUM_PT\n");
printf("%d\n", num_pt);
printf("#coordinates\n");
for (i = 0; i < num_pt; i++)
{
printf("%d\t%d\n", x_coordinate[i], y_coordinate[i]);
}
printf("#end of instance\n");
}
free(x_coordinate);
free(y_coordinate);
return 0;
}
I am wondering how I can read the name of the input file from bash terminal. Should I use scanf?
how do I get what the user has inputted as the input file? Like for example if the user is running my program from bash with ./myprogram -i instance10_001.txt, how can I open the inputted file in my program?
PS I am using my Ubuntu terminal to access my lab computer via ssh.
Language: c99 ; Compiler: gcc
This looks like a simple error in your if statment. You're saying if, and only if, inputfile is 1 (which means -o must have been argv[0]) it will open inputfile.
if (inputfile == 0)
{
/* invalid command line options */
printf("\nIncorrect command-line\n");
printf("myprogram [-i inputfile [-o outputfile]]");
return -1;
}
else /* if inputfile is not equal to 0, then this will execute. */
{
fp = fopen(argv[inputfile], "r");
}
Also, there's another problem here, in which you assign fp to a function and then reopen the file already opened in fp:
/* removed fp = fopen (a function) */
if (fp == NULL) /* You already opened the file; no need to open again until fclose */
{
/* open file error */
return -2;
}
Also, in this block of code:
while (fscanf(fp, "%d", &x_coordinate[i]) != 1)
{
if (ferror(fp))
{
/* read error */
fclose(fp);
return -8;
}
if (feof(fp))
{
/* no integer to read */
fclose(fp);
return -9;
}
fscanf(fp, "%*[^\n]"); /* skip the rest of line */
}
Fscanf returns the number of arguments successfully filled, which in this case, will always be 1.
Note that similar problems may be present in the remainder of the code.
The problem I am having is that whenever I run the code I get the Null value for myfile before I even get to pass the file name as the argument into the program and i'm not sure why any help is much appreciated.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE* myFile; // file pointer
myFile = fopen(argv[1] , "r"); //open file
if(myFile==NULL)
{
printf("Can't Open FIle.\n"); // if file doesn't exist then exit
exit(0);
}
int A[10000]={0};
int B[10000]={0};
double C[10000]={0};
int N,M;
int i=0;
fscanf (myFile, "%d", &N); //input N from file
printf("%d\n",N);
if(N>100)
{
exit(0); // if N>100 then exit
}
while (!feof (myFile)) // loop until file pointer reaches to the end of file
{
fscanf (myFile, "%d", &A[i]); //input source
fscanf (myFile, "%d", &B[i]); // input destination
fscanf (myFile, "%lf", &C[i]); // input time
i++;
}
fclose (myFile); //close file
M=i; // number of lines = M
for (i = 0; i < M; i++)
{
if(A[i]==0) //end of output
break;
else
{
printf("%d %d %lf:\n",A[i],B[i],C[i]); //print source, destination and time
if(A[i]>=1&&A[i]<=N)
{
if(B[i]>=1&&B[i]<=N)
{
if(A[i]==B[i])
{
printf("Error:Source city is the same as destination city.\n"); //same source and destination error:condition
}
else
{
if(C[i]<0)
{
printf("Error:Invalid Time.\n"); //invalid time
}
else
{
//
}
}
}
else
{
printf("Error: Invalid destination city.\n"); //invalid destination condition
}
}
else
{
printf("Error: Invalid source city.\n"); //invalid source condition
}
}
}
return 0;
}
If you don't pass a file name as an argument to the program, the contents of argv[1] are undefined.
Since anything could be there in argv[1] when the program attempts to open the file, the most probable thing is that there is no file with that name, and hence fopen() returns NULL.
You should not try to access command line arguments without checking that they were supplied, for that check argc, if you just expect 1 argument, then a simple check would be
char filename[256]; /* the size should be reasonable
* can be PATH_MAX or MAX_PATH,
* depending on whether it's Windows
* or not
*/
if (argc < 2)
{
size_t length;
fprintf(stdout, "Error: %s program expects one argument\n", argv[0]);
fprintf(stdout, "Please input the file name: ");
if (fgets(filename, sizeof(filename), stdin) == NULL)
{
fprintf(stdout, "Error: unexpected error\n");
return -1;
}
length = strlen(filename);
if (length == 0)
{
fprintf(stdout, "Error: the provided file name is invalid.\n");
return -1;
}
if (filename[length - 1] == '\n')
filename[length - 1] = 0;
}
else
strcpy(filename, argv[1]);
I am trying to read two files in my program I wrote earlier, but it always fails.
char line[BUFSIZ];
FILE *fp2=freopen("source.dat","r");
if(fp2==NULL)
printf("Problm opening: source.dat");
FILE *fp3=freopen("result.dat", "r");
if(fp3==NULL)
printf("Problm opening: result.dat");
char line2[BUFSIZ];
int len;
while( (fgets(line2, BUFSIZ, fp2) != NULL) && (fgets(line, BUFSIZ, fp3) != NULL)) {
len=strlen(line);
if( line[len - 1] == '\n' ) line[len-1] = '\0'; len=strlen(line2);
if( line2[len - 1] == '\n' ) line2[len-1] = '\0';
rename(line, line2);
}
I'm not sure why, I know my program writes the two files I want to open. It just doesn't get past the while loop.
freopen takes 3 arguments viz., filename, mode and FILE Stream object. Hence, to reopen a file, it should already be open. If we invoke a freopen as the first call, the runtime may throw an exception of uninitialized access.
Modifying the code as below
fp2 = fopen("source.dat", "r");
fp3 = fopen("result.dat", "r");
I am able to run your code without any problem and control continues beyond the while loop. The files stored in first file are renamed to the names stored in second file, which I presume is the objective of your program.
This code works for me and apparently should do the same yours does, except where noted.
The first note apparently was the right one :-)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char line[2][BUFSIZ];
FILE *fp[2];
char *file[2] = { "source.dat", "result.dat" };
int f, finished = 0;
// Any pointers to source and result must be flushed and closed at this point,
// i.e. if this same program has created the files, it must now close them.
for (f = 0; f < 2; f++)
{
if (NULL == (fp[f] = fopen(file[f],"r")))
{
fprintf(stderr, "Error opening %s\n", file[f]);
exit(-1);
}
}
while(!finished)
{
int len;
for (f = 0; f < 2 && (!finished); f++)
{
if (NULL == fgets(line[f], BUFSIZ, fp[f]))
{
fprintf(stderr, "NULL on %s\n", file[f]);
finished = 1;
break;
}
if (feof(fp[f]))
{
fprintf(stderr, "end of %s\n", file[f]);
finished = 1;
break;
}
len = strlen(line[f]);
// if one of the file contains an empty line, program might crash
if (0 == len)
{
fprintf(stderr, "empty line in %s\n", file[f]);
finished = 1;
break;
}
if ('\n' == line[f][len-1])
line[f][len-1] = 0x0;
}
if (finished)
break;
fprintf(stderr, "Rename(%s, %s)\n", line[0], line[1]);
// rename(line, line2);
}
for (f = 0; f < 2; f++)
fclose(fp[f]);
return 0;
}