I'm trying to get a program to parse a text file line by line for some data storage (I've tried binary file storage, but having mixed data types in the file seems to mess things up).
I'm trying to save a number of entries contained in hist[], which is an array of the history structure which basically contains a float (.value) and a time_t (.event_Time). Before saving these entries, the number of entries should be saved (currently an int).
So far I can write the file just fine using the following function:
void data_save(int node_Id, int sensor_Id, history *hist, int entries){
FILE *file;
char data_Dir[FILENAME_MAX] = "";
char directory[FILENAME_MAX] = "";
char fileName[FILENAME_MAX] = "";
int length = 0;
//define path of the file
_getcwd(data_Dir, FILENAME_MAX);
strcat(data_Dir, "\\Data");
strcat(directory,"\\Node_");
length = snprintf(NULL, 0,"%d",node_Id);
char str1[length];
sprintf(str1, "%d", node_Id);
strcat(directory,str1);
strcat(fileName,"\\Sensor_");
length = snprintf(NULL, 0,"%d",sensor_Id);
char str2[length];
sprintf(str2, "%d", sensor_Id);
strcat(fileName,str2);
strcat(fileName,".txt");
printf("%s\n", directory);
printf("%s\n", fileName);
//check if the Data directory exists, create it if not
if (directory_exists(data_Dir) == false) {
printf("Making directory\n");
_mkdir(data_Dir);
}
strcat(data_Dir, directory);
//check if the Node directory exists, create it if not
if (directory_exists(data_Dir) == false) {
printf("Making directory\n");
_mkdir(data_Dir);
}
strcat(data_Dir, fileName);
printf("%s\n", data_Dir);
//open the file
file = fopen(data_Dir, "w");
if(file == NULL){
printf("Error while opening file.\n");
exit (1);
}
//Save the number of entries
printf("Saving %d entries\n", entries);
fprintf(file, "%d\n", entries);
//Save each entry in the inverse chronological order
//(ie. latest event first)
for(int i=entries-1; i > -1; i--){
fprintf(file, "%f %ld\n", hist[i].value, hist[i].event_Time);
}
fclose(file);
free(data_Dir);
free(directory);
free(fileName);
printf("Node %d, sensor %d: Data saved Successfully (%d Entries)\n", node_Id, sensor_Id, entries);
return;
}
However, I am getting issues when trying to load the file I've just created using the following function:
history * data_load(int node_Id, int sensor_Id, int *entries){
FILE *file;
char data_Dir[FILENAME_MAX] = "";
char directory[FILENAME_MAX] = "";
char fileName[FILENAME_MAX] = "";
int length = 0;
int entries_Temp;
int maxChar = 1000;
char stream[maxChar];
//define path of the file
_getcwd(data_Dir, FILENAME_MAX);
strcat(data_Dir, "\\Data");
strcat(directory,"\\Node_");
length = snprintf(NULL, 0,"%d",node_Id);
char str1[length];
sprintf(str1, "%d", node_Id);
strcat(directory,str1);
strcat(fileName,"\\Sensor_");
length = snprintf(NULL, 0,"%d",sensor_Id);
char str2[length];
sprintf(str2, "%d", sensor_Id);
strcat(fileName,str2);
//check if the Data directory exists, exit if not
if (directory_exists(data_Dir) == false) {
printf("//Data does not exist\n");
*entries = 0;
return NULL;
}
strcat(data_Dir, directory);
//check if the Node directory exists, exit if not
if (directory_exists(data_Dir) == false) {
printf("//Data//Node%d does not exist\n", node_Id);
*entries = 0;
return NULL;
}
strcat(data_Dir, fileName);
printf("%s\n", data_Dir);
//check if file exists (ie. there has been no previous
//data for the given sensor) exit and return 0
//existing entries
file = fopen(data_Dir, "r");
if(file!=NULL){
printf("No file found for given sensor\n");
*entries = 0;
return NULL;
}
//Read the number of entries in the file
printf("Reading number of entries\n");
printf("%s", fgets(stream, sizeof(stream), file));
printf("%s\n", stream);
*entries = strtol(stream, NULL, 10);
printf("Entries : %d\n", *entries);
if(*entries > 100){
printf("Entries is NOK\n");
exit(1);
}
//create the array of structures containing the data
printf("Creating the data array\n");
history *hist = malloc(*entries * sizeof(history));
//Read the data and copy it to the array
//this has not been tackled yet
printf("Closing file\n");
fclose(file);
printf("Freeing memory (filenames...)\n");
free(data_Dir);
free(directory);
free(fileName);
printf("Node %d, sensor %d: Data loaded Successfully (%d Entries)", node_Id, sensor_Id, *entries);
return hist;
}
From what I can gather, it seems fgets returns NULL every time. I am unsure if the file is being read correctly, but it seems that the program manages to open the file as fopen returns non NULL. I also suspect that my first attempt at this using binary files might have failed for similar reasons, but due to the format, I couldn't check if the error was occuring during writing or reading of the file.
I'd like to get some insight on why fgets is failing. I'd also appreciate any guidance on better ways to handle saving and loading data from files, as I'm only a beginner in C and I'm pretty sure there's some more optimal ways of doing what I'm trying to achieve.
At least these problems:
Off by 1.
With a short buffer, sprintf(str1, "%d", node_Id); is undefined behavior (UB) and rest of code is all suspect.
length = snprintf(NULL, 0,"%d",node_Id);
// char str1[length];
char str1[length + 1];
sprintf(str1, "%d", node_Id);
...
//char str2[length];
char str2[length+1];
Bad free
Do not call free() on something that lacks a matching *alloc().
//free(data_Dir);
//free(directory);
//free(fileName);
Suggest simplify string code.
E.g. filename
char fileName[FILENAME_MAX];
int length = snprintf(fileName, sizeof fileName, "%s%d%s",
"\\Sensor_", sensor_Id, ".txt");
if (length < 0 || length >= sizeof fileName) {
Handle_BufferTooSmall_Error();
}
else {
printf("%s\n", fileName);
}
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.
In this code snippet I'm trying to add a string in a binary file. If the string already exists, I return error, otherwise I add it at EOF. I creataed two functions, void AddNewTeam(FILE* fp, char* newTeam), and int SearchTeam(FILE* fp, char* newTeam) as shown below, but that didn't work. Everytime I enter a string, it is added at EOF, even if is in the binary file.
I think the problem is the fread function, I tried to print the value returned by the fread but it is always 0. Can someone help me trying to understand what's wrong with this code and why it's not working?
void AddNewTeam(FILE* fp, const char* newTeam){
int found;
if((fp = fopen("File.dat", "rb")) == NULL){
fp = fopen("File.dat", "ab");
fclose(fp);
}
printf("\tEnter New Team: ");
scanf("%s", newTeam);
found = SearchTeam(fp, newTeam);
if(found == 0){
if((fp = fopen("File.dat", "ab"))){
fwrite(newTeam, sizeof(newTeam), 1, fp);
printf("\tThe following team has been successfully loaded\n");
fclose(fp);
}
}else if(found == 1){
printf("\tThis team already exists\n");
exit(EXIT_FAILURE);
}
}
int SearchTeam(FILE* fp, const char* newTeam){
char string[MAX][MAX_LENGTH];
int counter, result, found = 0;
if((fp = fopen("File.dat", "rb"))){
fseek(fp, 0, SEEK_SET);
for(counter = 0; !feof(fp); counter++){
if(fread(string[counter], sizeof(string[counter]), 1, fp) == 1){
result = strcmp(newTeam, string[counter]);
if(result == 0){
found = 1; break;
}else if(result != 0){
found = 0;
}
}
}
fclose(fp);
return found;
}else if(fp == NULL){
printf("\tError opening binary file\n");
exit(EXIT_FAILURE);
}
}
This is the main function and the function prototypes
int SearchTeam(FILE* fp, const char* newTeam);
void AddNewTeam(FILE* fp, const char* newTeam);
int main(void){
FILE* fp;
char newTeam[MAX_LENGTH];
AddNewTeam(fp, newTeam);
return 0;
}
You're not appending to the file correctly. The search code expects each team name to be in a block of MAX_LENGTH bytes. But when you write, you do:
fwrite(newTeam, sizeof(newTeam), 1, fp);
newTeam is a pointer, not an array, so sizeof will be the size of a pointer, typically 4 or 8 bytes. You need to write MAX_LENGTH bytes so this will match the way you read from the file.
fwrite(newTeam, MAX_SIZE, 1, fp);
I'm new at programming, and I need help in my C project. I have to search for a city, confirm it exists in the first file (city.csv), and take its id from there. Then I have to match that id with the corresponding one in the second file (meteo.csv), and then edit its weather information, that is in that second file. However, I don't know how I can take the city id from the first file, and then how to edit the second file after obtaining all the new weather informations. Here is the code:
void addInfo() {
FILE * fp;
char id_city[100];
char city[100];
char humidity[100];
char temp_max[100];
char temp_min[100];
char pressure[100];
char date[100];
printf("Name of the city: ");
scanf("%s", city);
// I think it's here that I have to write the code for take the city's id from the first file
if (id_city != NULL) {
printf("Maximun temperature: ");
scanf("%s", temp_max);
printf("Minimun temperature: ");
scanf("%s", temp_min);
printf("Humidity: ");
scanf("%s", humidity);
printf("Pressure: ");
scanf("%s", pressure);
printf("Date, in the format YYYY-MM-DD: ");
scanf("%s", date);
fp = fopen ("meteo.csv", "a");
fprintf(fp, "%s, %s, %s, %s, %s \n", temp_max, temp_min, humidity, pressure, date); //I think there's something wrong here too...
fclose(fp);
printf("Information edited successfully");
}
The file city.csv has 152 lines and 4 columns:
(id_city,city,county,district)
such as
(56,Lisbon,Lisbon,Lisbon)
The file meteo.csv has 152 lines and 7 columns:
(id_meteo_city,id_city,temp_max,temp_min,humidity,pressure,date)
such as
(56,56,14,5,62,1025,2018-02-12)
The first thing I would do is encapsulate the data in a struct, that makes it
easier to map a line of a CSV file into an object representing a line.
If both files city.csv and meteo.csv have different columns, I'd create a
different struct for each file. If both files have the same columns, you could
use the struct. I assume that both files are different and that city has the
format meteo_id,city_id,name.
typedef struct city_t {
int meteo_id;
int city_id;
char name[100]; // no city should have
// longer than 100 chars
} city_t;
typedef struct meteo_t {
int meteo_id;
int city_id;
int tempt_max;
int tempt_mix;
double humidity;
double preassure;
char date[11];
} meteo_t;
Let's assume that both files are well formatted, otherwise you would have to
write code that checks for errors and handles them, that would be the next step
in the exercise, so I'm going to write only the basic version with basic error
recognition.
#include <stdio.h>
#include <string.h>
#include <errno.h>
// takes 2 params, the filename and a pointer
// to size_t where the number of cities is stored
city_t *read_cities(const char *filename, size_t *len)
{
if(filename == NULL || len == NULL)
return NULL;
FILE *fp = fopen(filename, "r");
if(fp == NULL)
{
fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
return NULL;
}
city_t *arr = NULL, *tmp;
*len = 0;
// assuming that no line will be longer than 1023 chars long
char line[1024];
while(fgets(line, sizeof line, fp))
{
tmp = realloc(arr, (*len + 1) * sizeof *arr);
if(tmp == NULL)
{
fprintf(stderr, "could not parse the whole file %s\n", filename);
// returning all parsed cities so far
if(*len == 0)
{
free(arr);
arr = NULL;
}
return arr;
}
arr = tmp;
// %99[^\n] is to read up to 99 characters until the end of the line
if(sscanf(line, "%d,%d,%99[^\n]", &(arr[*len].meteo_id),
&(arr[*len].city_id), arr[*len].name) != 3)
{
fprintf(stderr, "Invalid line format (skipping line):\n%s\n", line);
// skip this line, and decrement *len
(*len)--;
continue;
}
// incrementing only when parsing of line was OK
(*len)++;
}
fclose(fp);
// file is empty or
// all lines have wrong format
if(*len == 0)
{
free(arr);
arr = NULL;
}
return arr;
}
void print_cities(city_t *cities, size_t len, FILE *fp)
{
if(cities == NULL || fp == NULL)
return;
for(size_t i = 0; i < len; ++i)
fprintf(fp, "%d,%d,%s\n", cities[i].meteo_id, cities[i].citiy_id,
cities[i].name);
}
Now I've written the read and write functions for the file citiy.csv assuming the
format meteo_id;city_id;name. The print_cities allows you to print the CSV
content on the screen (passing stdout as the last argument) or to a file
(passing a FILE object as the last argument).
You can use these functions as templates for reading and writing meteo.csv, the
idea is the same.
You can use these function as follows:
int main(void)
{
size_t cities_len;
city_t *cities = read_cities("city.csv", &cities_len);
// error
if(cities == NULL)
return 1;
do_something_with_cities(cities, cities_len);
// update csv
FILE *fp = fopen("city.csv", "w");
if(fp == NULL)
{
fprintf(stderr, "Could not open city.csv for reading: %s\n",
strerror(errno));
free(cities);
return 1;
}
print_cities(cities, cities_len, fp);
fclose(fp);
free(cities);
return 0;
}
Now for your exercise: write a similar function that parses meteo.csv (using
my function as a template shouldn't be that difficult) and parse both files. Now
that you've got them in memory, it's easy to manipulate the data (insert,
update, delete). Then write the files like I did in the example and that's it.
One last hint: how to search for a city:
// returns the index in the array or -1 on error or when not found
int search_for_city_by_name(city_t *cities, size_t len, const char *name)
{
if(cities == NULL || name == NULL)
return -1;
for(size_t i = 0; i < len; ++i)
if(strcmp(name, cities[i].name) == 0)
return i;
// not found
return -1;
}
Now I have given you almost all parts of the assignment, all you have to do is
stick them together and write the same functions for the meteo.csv file.
To edit one field:
void _ERR(char a) {
if (a == "f") printf("\n\tError File !!\n\n");
if (a == "m") printf("\n\tError Memory !!\n\n");
exit(1); }
char* stmm(const char* src) {
char* dst = malloc(strlen(src) + 1);
if (dst == NULL) return NULL;
strcpy(dst, src);
return dst; }
const char* getfield(char* line, int num) {
const char* tok;
for (tok = strtok(line, ",");
tok && *tok;
tok = strtok(NULL, ",\n"))
{
if (!--num)
return tok;
}
return NULL; }
void edit_file(char* FName, char* NewValue, int row, int col) {
int i, r = 0, c;
char line[1024];
FILE* fr, * fw;
fr = fopen(FName, "r");
fw = fopen(FName, "r+");
if (fr == NULL|| fw == NULL) _ERR("f");
while (fgets(line, 1024, fr))
{
char* tmp = stmm(line);
if (tmp == NULL) _ERR("m");
for (i = 0, c = 1; i < strlen(tmp); i++) {
if (tmp[i] == 44) c++;
}
for (i = 0; i < c; i++) {
if (r == row && i+1 == col) {
fprintf(fw,"%s", NewValue);
} else {
free(tmp);
tmp = stmm(line);
if (tmp == NULL) _ERR("m");
fprintf(fw,"%s", getfield(tmp, i + 1));
}
(i < c - 1) ? fprintf(fw,",") : fprintf(fw,"\n");
}
free(tmp);
r++;
}
fclose(fr);
fclose(fw); }
edit_file(".\FileName.csv","NewValue",Row,Column);
I don't get any error yet when I am trying to get value from array the program fails. The program contains a function to read products from file and store them in array of of type typedef structure item.
This is how the program looks like:
item *displayProducts(int balance){
int row=0;
char line[MAX_LINE_SIZE + 1]; // ptr to the current input line
static item products[8];
FILE *fp;
fp = fopen("machinedata.txt", "r");
if (fp == NULL)
{
printf("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
while (fgets(line, MAX_LINE_SIZE, fp)) {
char *next_ptr = NULL;
char *next_item = strtok_s(line, ",;", &next_ptr);
while (next_item != NULL){
char *item_ptr = NULL;
char *name = strtok_s(next_item, "-", &item_ptr);
if (name == NULL)
{
fprintf(stderr, "Failed to scan name out of [%s]\n", next_item);
break;
}
int price;
next_item = strtok_s(NULL, " ,", &item_ptr);
//assert(next_item != NULL);
if (strcmp(name," ")){
if (sscanf(next_item, "%d", &price) != 1)
fprintf(stderr, "Failed to convert [%s] to integer\n", next_item);
else if (balance > price){
products[row].name = name;
products[row].price = price;
products[row].product_code = row + 1;
printf("%d) %s:%d\n",products[row].product_code, products[row].name, products[row].price);
row++;
}
next_item = strtok_s(NULL, ",;", &next_ptr);
}
}
}
fclose(fp);
return products;
}
void main( int argc, char *argv[]){
int *ptr_to_balance;
int balance = atoi(argv[2]);
ptr_to_balance = &balance;
item *ptr_to_products;
Init(argv[1], balance);
ptr_to_products = displayProducts(balance);
printf("%s", *(ptr_to_products[2].name));
}
the program will print out all of the products from the file but for some reason the last line of the program fails. Any idea why?
I think, you need to change
printf("%s", *(ptr_to_products[2].name));
to
printf("%s", ptr_to_products[2].name);
as %s expects a pointer-to-null-terminated char array.
All the pointers in your products array point into the line array. This has two problems:
This array is local to displayProducts, and it's destroyed when the function returns.
Each element of products is has pointers to the same line array. So when you read a new line from the file, you're overwriting the values that were saved in the previous elements of products.
You need to make a copy of name in the heap before you save it in products[row].
char *name_copy = malloc(strlen(name)+1);
strcpy(name_copy, name);
products[row].name = name_copy;
You also need to fix the printing code, as in the other answer:
printf("%s", ptr_to_products[2].name);
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.