Opening files in C in Xcode - c

#include <stdio.h>
#include <math.h>
int main(void) {
int i=0;
int number =0;
float vector[100];
float sum=0., mean = 9., stdev=0.;
FILE *fp_in = NULL;
fp_in = fopen("stat_data.txt","r");
if(fp_in != NULL)
{
fscanf(fp_in,"%d",&number);
for (i=0; i < number; i++)
{
fscanf(fp_in, "%f", &vector[i]);
sum += vector[i];
}
mean = sum/number;
printf("Mean = %f\n",mean);
sum=0.0;
for(i=0; i<number;i++)
{
sum+= pow(vector[i]-mean,2);
}
stdev = sqrt(sum/(number - 1));
printf("standard deviation is %f\n", stdev);
}
else
{
printf("Opening of file stat_data.txt failed\n");
}
return 0;
}
I'm trying to open the text file "stat_data" in Xcode and it works on a linux computer, but it doesn't seem to work on Xcode. I think there's something wrong with the settings but I don't know what it could be.
Screenshot of the IDE showing where the stat_data.txt is placed -

This happened because the place where the Xcode created de binary file is different where your txt file is locate.
So I put my txt file in the same directory of my binary (readFile).
In the picture I list where my source and binary file are locate.
If you don't know where your binary file is. You can show it f you don't know where your binary file is. You can show it using the "show in finder".
So my result is it:
File opened.

Because you do not specify a path to the file name when you open it, the program expects the file to be in the current working directory which is set by Xcode when you run the program in Xcode and set by the shell when you run the program from the command line (as the directoy you are in when you run it).
There are two ways to get around this:
specify an absolute path when you open the file e.g.
/Users/thiagmarques/path/to/stat_data.txt
Edit the scheme to run from the directory containing the file. If you click on "Edit Scheme" and then select the Run section. The Options tab has a check box to "Use custom working directory". Check this and enter the directory containing your text file.

Related

Properties file reading in C (no C# or C++) compiled with minGW

I need to say that i am Newbie at C and i only wrote about 100-150 lines of code in C.
I need to read a .properties file with entries like the following:
Value1 = Hello
Value2 = Bye
I would like to get to the Values like this:
bla.getValue("Value1");
So i can work with it like this:
foo = bla.getValue("Value1");
bar = bla.getValue("Value2");
printf("%s - %s",foo,bar);
I don't need them for anything else, than printing them to the screen.
I found two questions here, which went into the right direction, but they couldn't help me in my task:
How to read configuration/properties file in C?
Properties file library for C (or C++)
I tried multiple of the answers of the thread above, but either way my compiler(minGW) doesn't like one of these lines:
using foo::bar;
or
using namespace foo;
When i try to compile my code, i get an error saying:
error: unknown type name 'using'
This is the code where i tried to implement the given solution of the thread above:
#include <windows.h>
#include <stdio.h>
#include <string.h>
using platformstl::properties_file;
int WINAPI WinMain(HINSTANCE a,HINSTANCE b,LPSTR c,int d)
{
char *tPath, *tWindow;
char *search = " ";
tWindow = strtok(c, search);
tPath = strtok(NULL, search);
properties_file properties("%s",tPath);
properties::value_type value1 = properties["Value1"];
properties::value_type value2 = properties["Value2"];
printf("Window: %s; Path: %s; %s %s",tWindow,tPath,value0,value1);
}
I use a WinMain, because the programm is about finding an open Window. I haven't included those parts of the code, because they are irrelevant for my question and worked completely fine. The strtok(); parts are working fine for me too. I need them, because the title of the window to find and the Path of the properties file are both given as commandline arguments:
programm.exe windowtitle path/to/properties/file
As i tried with other answers, which told me to load some libraries, i got to a point, where the needed libraries didn't contain the needed header files. Some of the libraries are even for c++, which i have a restriction on, so i can't use it.
I hope that made things a little clearer, as you may know that i am not used to ask questions here. :)
I solved my Problem with a big Workaround.
This is my final code:
if(vn != NULL){
for(i = 0; i < 1; i++){
if(fgets(temp, BUF, vn) == NULL){
printf("Line is empty");
return 2;
}
}
if(fgets(puffer, BUF, vn) == NULL){
printf("Line is empty");
return 2;
}
tVariable = strtok(puffer, find);
tValue = strtok(NULL, find);
}else {
printf("Unable to read File");
return 2;
}
I just read the second Line of the given file and cut it at the = sign.
I know, that i need to read the second line, because the Property i need is always found in the second line of the .properties file.
I now have my wanted Value in tValue, so i can use it to print it out with printf("%s", tValue).

Running a terminal command from a C program in OS X

I'm trying to use plotutils to generate a plot from binary data. First, I wrote a C program to export some sample binary data. Then, when I execute the following command in terminal, the plot gets generated as expected.
graph -T png -I d <'/Users/username/Documents/Restofpath/PlotutilsDataGen/testData'> '/Users/username/Documents/Restofpath/PlotutilsDataGen/testPlot.png'
But I want to combine this command with the C code that generates the binary data file so that once the code is executed, the plot is automatically exported. I tried two approaches: (i) using popen() which I suspect I'm doing incorrectly, and (ii) using system() which I thought should work, but doesn't. My entire code is as follows (I've listed both approaches together in the code by I naturally tried them individually):
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int numSamples = 1024;
double outputVec[2*numSamples];
char outputPath[200] = "/Users/username/Documents/Restofpath/PlotutilsDataGen/testData";
char plotcommand[400] = "graph -T png -I d <'/Users/username/Documents/Restofpath/PlotutilsDataGen/testData'> '/Users/username/Documents/Restofpath/PlotutilsDataGen/testPlot.png'";
FILE *fp, *p;
// Compute sample functions to export
for(int ii = 0; ii < (2*numSamples); ii = ii + 2)
{
outputVec[ii] = (double)ii/2;
outputVec[ii+1] = (double)(ii*2);
}
// Export as binary data file for plotutils to use for plotting
fp = fopen(outputPath, "wb");
fwrite(outputVec, sizeof(double), 2*numSamples, fp);
fclose(fp);
// Option 1
p = popen(plotcommand, "w");
pclose(p);
// Option 2
system(plotcommand);
return 0;
}
Any ideas as to what I'm doing wrong or how I might get this to work? Thanks.

C programming and OpenCV (How to read an image from a file and load it for further processing in openCv)

I have created a file in C which contains the filemanes of images. The code is given below ("Leaves" is a dataset of images. I am storing the image names in a file):
FILE *fp;
system("dir /B D:\\opencvprojects\\platphenotypeFinal\\platphenotypeFinal\\Leaves > file.txt");
file.txt looks like this:
1001.jpg
1002.jpg
1003.jpg
1004.jpg
1005.jpg
1006.jpg
1007.jpg
Now I want to read each image from the file, do the background subtraction in openCV and save the results for all these images in another file.
OriginalImage=cvLoadImage("Leaves\\1007.jpg",CV_LOAD_IMAGE_GRAYSCALE);
I know how to read a single image (using the above code), but I want to automatically read each image of the file, do the processing, and save the result in another file, and the process continues in a loop until all images are taken care of.Thus, an output file will be generated containing the file names (same as the input file names) of binary images.
Your help will be very much appreciated.
int main()
{
CvMoments moments;
CvMemStorage *connectedCompStorage = cvCreateMemStorage (0);
CvSeq *temp = NULL; //used to loop through contour perimeter checking
CvSeq *connectedComp = NULL;
FILE *fp;
char buffer[9];
system("dir /B D:\\opencvprojects\\platphenotypeFinal\\platphenotypeFinal\\Leaves > file.txt");
fp = fopen ("file.txt", "r+");
OriginalImage = cvLoadImage("Leaves\\1108.jpg",CV_LOAD_IMAGE_GRAYSCALE);
}
opencv has a nice glob function to read a whole directory:
(and please, do not use opencv's C-api !)
vector<String> files;
glob("D:\\opencvprojects\\platphenotypeFinal\\platphenotypeFinal\\Leaves\*.jpg", files);
for (size_t i=0; i<files.size(); i++)
{
Mat m = imread(files[i]);
// process image
}

Create temporary file in C, MS Windows system

Basically, i have a program that is given a 4 meg compressed file, it has to decode this file into uncompressed ~ 100 meg, then compress it back into ~4 meg file. I need to store this intermediate 100 meg file somewhere on the drive (dont want to keep it in memory).
Program is written in C and will be executed on MS Windows 7. At the moment of uncompressing, no guaranteed folder (with write access) is given to the program (folder with source file might be read only and folder with target file might be not yet specified).
This has proven to be not an easy task:
1) I have read about a C function that creates a temp file that will disappear when closed or program is terminated. However, from what i understand it tries to make the file on disk C, in root directory, so this will obviously fail if user has no rights for that (which normal user doesnt)
2) I had an idea to use environmental/system variable TEMP and create a file there, BUT looking on a random Win7 PC which wasnt tweaked, i see that this variable points to c:/windows/temp, and that folder has specific rights for "users" - that is, they have rights to read, execute, create and write files, but not to delete them, check their attributes, etc. This means, i assume, that if program is ran with user privilleges, it will be able to make a file but not able to delete it, so the only way to "delete" it would be to open the file for writing and then close it, making it a 0 length file. This is also not desired, and i dont know how to query for system variables from C
3) So, basically, only idea i have right now is to make a function to open file that:
tries to create a temp file in the output dir, if possible
if failed, tries to create a temp file in input dir
if failed, tries to create a temp file in TEMP dir from system variable
if failed, tries to create a temp file in TMP dir from system variable
and a delete function that:
tries to remove() the file (by its name that is stored somewhere)
if failed, it tries to open the file for write, and close it, so it becomes a 0 byte file
Are there better ideas?
Any help is appreciated, thanks!
PS: Program must not use any external libraries like MFC or something, only built-in standart C functions
GetTempPath
Retrieves the path of the directory designated for temporary files.
GetTempFileName
Creates a name for a temporary file. If a unique file name is
generated, an empty file is created and the handle to it is released;
otherwise, only a file name is generated.
These two provide you easy way to obtain a location and name for a temporary file.
UPD: Code sample on MSDN: Creating and Using a Temporary File.
#include <windows.h>
#include <iostream>
#include <chrono>
#include <string>
#include <cstdio>
#include <chrono>
using namespace std;
int FileExists(string& filepath)
{
DWORD dwAttrib = GetFileAttributes(filepath.c_str());
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
!(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
int GetTemporaryFilePath(
string filePrefix,
string fileExt,
string& TmpFilePath /*return*/)
{
if (fileExt[0] == '.')
fileExt.erase(0,1);
char TempPath[MAX_PATH] = { 0 };
if (!GetTempPath(MAX_PATH, TempPath))
return -1;
uint16_t tickint = 0;
while(1) {
const int nowlen = 17; char nowstr[nowlen];
const int ticklen = 5; char tickstr[ticklen];
// Milliseconds since 1970
auto ms = chrono::duration_cast<chrono::milliseconds>(
chrono::system_clock::now().time_since_epoch()
);
__int64 nowint = ms.count();
snprintf(nowstr, nowlen, "%016" "I64" "x", nowint);
snprintf(tickstr, ticklen, "%04x", tickint);
TmpFilePath = string(TempPath)
+ filePrefix
+ "." + string(nowstr)
+ "." + string(tickstr)
+ "." + fileExt;
if (!FileExists(TmpFilePath)) {
//Touch File
FILE* w = fopen(TmpFilePath.c_str(), "w");
fclose(w);
break;
}
tickint++;
}
return 0;
}
int main()
{
string TmpFilePath;
GetTemporaryFilePath("MyFile", ".txt", TmpFilePath);
cout << "TmpFilePath: " << TmpFilePath << endl;
return 0;
}

Making C code plot a graph automatically

I have written a program which writes a list of data to a '.dat' file with the intention of then plotting it separately using gnuplot. Is there a way of making my code plot it automatically? My output is of the form:
x-coord analytic approximation
x-coord analytic approximation
x-coord analytic approximation
x-coord analytic approximation
x-coord analytic approximation
....
Ideally, when I run the code the graph would also be printed with an x-label, y-label and title (which could be changed from my C code). Many thanks.
I came across this while searching for something else regarding gnuplot. Even though it's an old question, I thought I'd contribute some sample code. I use this for a program of mine, and I think it does a pretty tidy job. AFAIK, this PIPEing only works on Unix systems (see the edit below for Windows users). My gnuplot installation is the default install from the Ubuntu repository.
#include <stdlib.h>
#include <stdio.h>
#define NUM_POINTS 5
#define NUM_COMMANDS 2
int main()
{
char * commandsForGnuplot[] = {"set title \"TITLEEEEE\"", "plot 'data.temp'"};
double xvals[NUM_POINTS] = {1.0, 2.0, 3.0, 4.0, 5.0};
double yvals[NUM_POINTS] = {5.0 ,3.0, 1.0, 3.0, 5.0};
FILE * temp = fopen("data.temp", "w");
/*Opens an interface that one can use to send commands as if they were typing into the
* gnuplot command line. "The -persistent" keeps the plot open even after your
* C program terminates.
*/
FILE * gnuplotPipe = popen ("gnuplot -persistent", "w");
int i;
for (i=0; i < NUM_POINTS; i++)
{
fprintf(temp, "%lf %lf \n", xvals[i], yvals[i]); //Write the data to a temporary file
}
for (i=0; i < NUM_COMMANDS; i++)
{
fprintf(gnuplotPipe, "%s \n", commandsForGnuplot[i]); //Send commands to gnuplot one by one.
}
return 0;
}
EDIT
In my application, I also ran into the problem that the plot doesn't appear until the calling program is closed. To get around this, add a fflush(gnuplotPipe) after you've used fprintf to send it your final command.
I've also seen that Windows users may use _popen in place of popen -- however I can't confirm this as I don't have Windows installed.
EDIT 2
One can avoid having to write to a file by sending gnuplot the plot '-' command followed by data points followed by the letter "e".
e.g.
fprintf(gnuplotPipe, "plot '-' \n");
int i;
for (int i = 0; i < NUM_POINTS; i++)
{
fprintf(gnuplotPipe, "%lf %lf\n", xvals[i], yvals[i]);
}
fprintf(gnuplotPipe, "e");
You can either create a gnuplot script and spawn a process running gnuplot to plot this script from the commandline, or you may use one of the provided interfaces. For C, there is a POSIX pipe-based interface from Nicolas Devillard available here:
http://ndevilla.free.fr/gnuplot/
...and an iostream-based C++ version is available via git (see: http://www.stahlke.org/dan/gnuplot-iostream/ )
The most portable and probably the easiest way would still be calling gnuplot to plot a script, though. As sje397 mentioned, check your documentation for the system() call in stdlib.h.
On a sidenote, there is also GNU plotutils, which offers libplot, a library for plotting datasets, which you could use in your application. See: http://www.gnu.org/software/plotutils/
Although I've seen a lot of ways of doing this, the most simplest way of doing this would be by using the system() (from stdlib.h) function in C.
First make a gnuplot script and save it as "name.gp" (neither the name nor the extension matter).
A simple script would be,
plot 'Output.dat' with lines
After saving this script file, just add
system("gnuplot -p name.gp");
at the end of your code.
It's as simple as that.
Make sure to add gnuplot path to the Windows System Path variables.
I've adapted the accepted answer to plot a float array while avoiding the use of a temporary file. In it, float* data_ is the array and size_t size_ its size. Hopefully it is helpful for someone!
Cheers,
Andres
void plot(const char* name="FloatSignal"){
// open persistent gnuplot window
FILE* gnuplot_pipe = popen ("gnuplot -persistent", "w");
// basic settings
fprintf(gnuplot_pipe, "set title '%s'\n", name);
// fill it with data
fprintf(gnuplot_pipe, "plot '-'\n");
for(size_t i=0; i<size_; ++i){
fprintf(gnuplot_pipe, "%zu %f\n", i, data_[i]);
}
fprintf(gnuplot_pipe, "e\n");
// refresh can probably be omitted
fprintf(gnuplot_pipe, "refresh\n");
}
I know it's too late, but answering if it may help someone.
fputs really does the job, you want. first you need to print the data you want to plot in a temporary file data.temp.
FILE *pipe_gp = popen("gnuplot -p", "w");
fputs("set terminal png \n",pipe_gp);
fputs("set output 'abc.png' \n",pipe_gp);
fputs("set xlabel 'f' \n",pipe_gp);
fputs("set xrange [0:100] \n",pipe_gp);
fputs("set yrange [0:100] \n",pipe_gp);
fputs("plot 'data.temp' u 1:2 w circles lc rgb 'pink' notitle \n",pipe_gp);
pclose(pipe_gp);

Resources