How to get all the content using fprintf in c - c

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.

Related

fprintf places in odd value when processing char value

I am writing what should be a simple program, but I'm having an odd issue with fprintf I have not been able to solve.
I am reading a small CSV text file and writing those values to a separate file containing only the numeric values.
My CSV file looks like this.
000,001,002,
003,004,005,
006,007,008,
009,010,011,
255,255,255
There is a comma between each value and a return at the end of each line.
The code I am using is
#include <stdio.h>
#include <string.h>
int main(int argc, char ** argv) {
FILE * inputFile;
FILE * outFile;
char * filename;
int records = 0;
char line[15];
char * sp;
char appendString[] = ".hex";
printf("useage: dec2hex inputFile.txt\n");
// Check if a filename has been specified in the command
if (argc < 2) {
printf("Missing Filename\n");
return (1);
} else {
filename = argv[1];
printf("Read in Filename : %s\n", filename);
}
// Open file in read-only mode
inputFile = fopen(filename, "r");
if (inputFile == NULL) {
printf("Hey! Failed to open the file\n");
return (1);
}
strcat(filename, appendString);
printf("write out filename : %s\n", filename);
outFile = fopen(filename, "w");
while (fgets(line, 15, inputFile) != NULL) {
sp = strtok(line, ",");
char Y_pos = atoi(sp);
sp = strtok(NULL, ",");
char X_pos = atoi(sp);
sp = strtok(NULL, ",");
char OType = atoi(sp);
//print to file
fprintf(outFile, "%c", Y_pos);
fprintf(outFile, "%c", X_pos);
fprintf(outFile, "%c", OType);
records++;
}
fprintf(outFile, '\0');
printf("records = %d\n", records);
fclose(inputFile);
fclose(outFile);
return (0);
}
This will write to a file ..hex
The output I'm expecting should be
000102030405060708090a0bffffff
However what I'm seeing is an odd value inserted $D0.
I'm expecting $0A which does happen afterwards. I have tried some other values in my CSV (from 0 to 50) and this for now seems to be the only value that is random.
The reason I'm using %c in my fprintf is that I only need values from 0-255.
My first question, is why the odd value when processing 010?
How can this be corrected?
I'm using the TCC compiler 0.9.26, but have gotten similar results when using VS.
Thanks
However what I'm seeing is an odd value inserted $D0 $0D.
File was opening in text mode and when writing a code 10 ('\n'), incurred a "\n" to "\r\n" translation on OP's machine.
Instead open the file in binary mode.
// outFile = fopen(filename, "w");
outFile = fopen(filename, "wb");
Note: Other code short-comings exist.
you do not this strtok and atoi magic or binary mode opening magic
int main(void)
{
char line[1000];
while (fgets(line, 100, stdin) != NULL)
{
int X,Y,O;
if(sscanf(line, "%d,%d,%d,", &Y, &X, &O) != 3) { /* error handling*/ }
else
{
printf("%02x ", Y);
printf("%02x ", X);
printf("%02x ", O);
}
}
}
https://godbolt.org/z/vvKGzdcvd

how to enter a function to a file in c

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.

C using a file as an argument

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]);

Cannot delete file in C

I am using Code Blocks and I would like to delete a file using C. The file is used by two functions but not simultaneously.
This is the first function which uses the file:
double FileRead()
{
double n,cl,cd,result;
FILE *fd;
char filename[] = "save.txt";
char buff[5024];
if ((fd = fopen(filename, "r")) != NULL)
{
fseek(fd, 0, SEEK_SET);
while(!feof(fd))
{
memset(buff, 0x00, 5024);
fscanf(fd, "%[^\n]\n", buff);
}
sscanf(buff, "%lf %lf %lf",&n,&cl,&cd);
printf("cl: %1.5f cd: %1.5f\n",cl,cd);
result = (cl/cd);
printf("The CL/CD ratio is : %1.5f\n",result);
}
else
result = 0;
fclose(fd);
return result;
}
And this is the second function:
void evaluate(void) /*evaluate the population */
{
int mem;
int i;
double x[NVARS+1];
char buffer[101] = "save.txt";
FILE *controlpoints;
double y[NVARS] = {1.00000,0.92544,0.82351,0.78301,0.74004,0.50199,0.40422,0.31056, /*fixed values on x axis */
0.18549,0.14954,0.11702,0.06331,0.02581,0.01334,0.00509,0.00000,0.00052,0.00555,0.03324,
0.11345,0.33088,0.43678,0.60146,0.70751,0.8043,0.92047,0.98713,1.00000};
for(mem = 0; mem < POPSIZE; mem++)
{
controlpoints = fopen("controlpoints2.txt","w");
for(i = 0; i < NVARS; i++)
{
x[i+1] = population[mem].gene[i];
fprintf(controlpoints,"%1.5f\n%1.5f\n",y[i],x[i+1]);
printf("The value of population[%d].gene[%d] is %f\n",mem,i,population[mem].gene[i]);
}
fclose(controlpoints);
rbspline();
XfoilCall();
population[mem].fitness = FileRead();
}
remove(buffer);
if(remove(buffer) == 0)
printf("File %s deleted.\n", buffer);
else
fprintf(stderr, "Error deleting the file %s.\n", buffer);
}
All the time I am getting the message "Error deleting the file save.txt". Can you please check it out and tell me what am I doing wrong?
Your code in the second function contains:
remove(buffer);
if (remove(buffer) == 0)
printf("File %s deleted.\n", buffer);
else
fprintf(stderr, "Error deleting the file %s.\n", buffer);
You're removing the file twice and the second time it isn't there, so you report failure.
Fix: remove the unchecked remove(buffer) line.
Look at this part of the code
remove(buffer);
if(remove(buffer) == 0)
printf("File %s deleted.\n", buffer);
else
I think you want this
ret=remove(buffer);
if(ret==0)
printf("File %s deleted.\n", buffer);
else

C: Too many files open

This code opens a directory, and for every file in the directory it loops through every line of data inside the file, and then parses it to do some calculations and outputs the resulting data into a new file.
The problem is that I can only output a maximum of around 1021 files. I'm closing all of the fopens after outputting all the data, so I'm not sure what I'm doing wrong.
Shouldn't fclose() be closing the open files therefore this not happening?
int main(int argc, char *argv[])
{
//sample data values
double lat;
double lon;
double convergence;
double pt_scale;
int zone = 54;
double major_axis = 6378137.0000;
double flattening = (1/298.2572);
double zoneWidth = 6;
double centMeridian = -177;
double falseEast = FALSE_EASTING;
double falseNorth = FALSE_NORTHING;
double scale = SCALE_FACTOR;
int max_size = 128;
int current_size = max_size;
char *pathStr = malloc(max_size);
char *outPathStr = malloc(max_size);
char coData[100]; //max length of line;
long firstTerm, secondTerm; //terms we will split the line into, lat, lon, elevation.
int counter = 0; //pos counter
int d = EOF; //end of file ASCII
char strIn[200];
char* elevation;
char strOut[200];
char dirOut[200]; //sprintf must use a actual defined buffer otherwise there will be a buffer overflow.
char* cchr;
int j;
_setmaxstdio(2048);
printf("Please enter the path of the files: \n");
getUserInput(pathStr, current_size, max_size);
printf("Please enter the output path of the files: \n");
getUserInput(outPathStr, current_size, max_size);
//loop through each file in the directory. Open the file, convert, then close it.
//we will use dirent.h as it is cross platform so we wont have to worry about sharing issues
DIR *dir; //new directory
struct dirent *ent;
dir = opendir(pathStr); //allcate it a path
if(opendir(pathStr) == NULL)
{ printf("Error: %d (%s)\n", errno, strerror(errno));}
int k;
if(dir != NULL)
{
while((ent = readdir(dir)) != NULL) //loop through each file in the directory.
{
//open the file and loop through each line converting it then outputing it into a new file
if((!strcmp(ent->d_name,"..") || !strcmp(ent->d_name,".")) == 1)
{
//dont want these directories
continue;
}
else
{
sprintf(strIn,"%s%s",pathStr,ent->d_name); //get the file n
FILE *fp = fopen(strIn, "r");
if(fopen(strIn, "r") == NULL) //for inputting file
{ printf("Error: %d (%s)\n", errno, strerror(errno));
getchar();
break; }
sprintf(dirOut,"%s%d%s",outPathStr,counter,".geo");
printf("%s \n",dirOut);
FILE *fp2 = fopen(dirOut, "w"); //for outputting file
if(fopen(dirOut, "w") == NULL)
{ printf("Error: %d (%s)\n", errno, strerror(errno));
getchar();
break; }
while(fgets(coData, 100, fp) != NULL)//loop through line by line, allocate into 2 doubles and a string, pass the two coordinates and convert
{
//extract terms from coData
char * pch; //pointer to array pos
char * pend;
pch = strtok(coData," ");
j = 0;
while(j <= 2) //We only want to split the first three parameters.
{
//convert char array to double for co-oridinate conversion
if(j == 0)
{
firstTerm = atof(pch); //latitude;
j++;
continue;
}
if(j == 1)
{
pch = strtok(NULL, " ");
secondTerm = atof(pch); //longitude
j++;
continue;
}
if(j == 2)
{
pch = strtok(NULL," ");
elevation = pch; //elevation doesnt need to be converted because it isnt used in the coordinate conversion.
break;
}
}
grid2spheroid(&lat,&lon,&convergence,&pt_scale,firstTerm,secondTerm,zone,0, major_axis,flattening,zoneWidth,centMeridian,falseEast,falseNorth,scale);
sprintf(strOut,"%f %f %s",lat,lon,elevation);
//printf("%d %d", lat, lon);
fputs(strOut,fp2);
} //end of while
fclose(fp2);
fclose(fp);
counter++;
}
}
closedir(dir);
}
free(pathStr); //finished using the path string so we can finish the
free(outPathStr);
getchar();
return 0;
}
void getUserInput(char *pathStr, int current_size, int max_size)
{
unsigned int i = 0;
if(pathStr != NULL)
{
int c = EOF;
//get the user input and reallocate the memory size if the input it too large.
while((c = getchar()) != '\n' && c != EOF) //WHILE NOT END OF FILE OR NEW LINE (USER PRESSED ENTER)
{
pathStr[i++] = (char)c;
if(i == current_size)
{
current_size = i+max_size;
pathStr = realloc(pathStr, current_size);
}
}
}
}
You aren't closing all the files ;-)
FILE *fp = fopen(strIn, "r");
if(fopen(strIn, "r") == NULL) //for inputting file
Same applies to your output.
I think you meant something more like:
FILE *fp = fopen(strIn, "r");
if(fp == NULL) //for inputting file
{
// error handling.
No, no! You're opening every file twice (and only closing once)!
/* Bad! */
dir = opendir(pathStr); //allcate it a path
if(opendir(pathStr) == NULL)
{ printf("Error: %d (%s)\n", errno, strerror(errno));}
int k;
/* Correct */
dir = opendir(pathStr); //allocate it a path
if(!dir) {
printf("Error: %d (%s)\n", errno, strerror(errno));
return;
}
You're also doing the same thing with fopen(). In both places :)
Just check the pointer; don't call "fopen()" a second time; don't call "opendir()" a second time!
Also: please don't put code on the same line as your opening brace. OK?
dir = opendir(pathStr); //allcate it a path
if(opendir(pathStr) == NULL)
(...)
FILE *fp2 = fopen(dirOut, "w"); //for outputting file
if(fopen(dirOut, "w") == NULL)
(...)
FILE *fp = fopen(strIn, "r");
if(fopen(strIn, "r") == NULL) //for inputting file
Here you open the file twice but only store the pointer once. Change these to:
FILE *fp = fopen(strIn, "r");
if(fp == NULL) //for inputting file
and the other one in the same way.

Resources