I have a little experience with Matlab, but am new to the mex environment.
What I am trying to do is to save some values I compute to a txt file in my C routine.
For the sake of simplicity I am using the example arrayProduct.c from MathWork's Create C Source File guide here to elaborate.
I modified the example code in the following way:
void arrayProduct(double x, double *y, double *z, mwSize n)
{
mwSize i;
/* multiply each element y by x */
FILE *f = NULL;
f = fopen("log_test.csv", "rb");
for (i=0; i<n; i++)
{
z[i] = x * y[i];
fprintf(f, "%g\n", z[i]);
}
fclose(f);
}
So I added the declaration of f, the fopen, the fprintf and the fclose commands.
I am using MS Visual Studio C++ 2013 Professional (C) as a compiler and the code compiles just fine.
Through uncommenting all my changes and introducing them bit by bit again I was able to find out that Matlab crashes at the fopen command.
I wasn't able to find useful help here or elsewhere, so any suggestions are very welcome. Thanks very much in advance!
Kind Regards
Philipp
Use w+ or r+ when using fopen, depending on what you want to do with the file and whethe you want to create it or simply open it.
From (http://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm)
"r" Opens a file for reading. The file must exist.
"w" Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.
"a" Appends to a file. Writing operations, append data at the end of the file. The file is created if it does not exist.
"r+" Opens a file to update both reading and writing. The file must exist.
"w+" Creates an empty file for both reading and writing.
"a+" Opens a file for reading and appending.
Thanks for the helpful comments, especially by RobertStettler!
The problem was with the mode I opened the file with. it should rather be r+, w+ or a+.
Related
So i'm trying updating data from original file to a new temporary file, then i remove the original file and rename the temp file with the name of the original one like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(){
FILE * fptr = NULL;
FILE * temp;
fptr = fopen("Original.txt", "rw+");
temp = fopen("temp.txt", "w");
if(fptr==NULL)//Check if file was opened successfully
{
printf("File could not be opened");
}
//cicle of me adding data to temp file
fclose(fptr);
fclose(temp);
remove("Original.txt");
rename("temp.txt","Original.txt");
return 0;
}
it works the first time, but when i execute again the Original.txt ends up blank. What can be causing that?
I've tried changing temp = fopen("temp.txt", "w"); to temp = fopen("temp.txt", "ab+"); but the info of Original.txt ends up with no spaces or new lines between (all together). And same with "wb"
"rb" the Original.txt file disappears.
if necessary ill add the entire code, althought i dont think its revelant
The moment you do an fopen (path, "w") it truncates the file pointed by the path. Then you close the file. Therefore essentially, your "temp.txt" is an empty file after the line fclose (temp). Get rid of the "w+" and "w" as they will truncate the file (make it zero length).
See man fopen
w Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
w+ Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned
at the beginning of the file.
You do not need to open and or close the file at all. If you see the remove and rename uses absolutely nothing from the previous part of the code. Also check man rename and man remove. If you want to know if the files are present of not. Check the return values of these functions. In case of error, you can always inspect the errno to understand what exactly went wrong. (See manpage for details).
Not sure what you are trying to do exactly, but depending on your question, you need only "r" mode for reading.
i.e, fptr = fopen("Original.txt", "r");
Additionally, couple of suggestions, but not answer to your question:
You are checking fptr == NULL, but proceeding to write data anyway? what if fptr == NULL is true and you try to read from a NULL pointer? Besides putting an error message, put a return -1 or something so that the program does not continue further for that case.
You should check temp == NULL as well, to detect whether file is opened for writing also. What if temp == NULL is true and you try to write to a NULL pointer?
I'm trying to read the contents of "Danfilez.txt" using fgets. However on completion the program returns a random value and i'm unsure why. I'm new to programming so any help would be greatly appreciated!
int main()
{
FILE* Danfile = fopen ("Danfilez.txt", "w");
char fileinfo [50];// Character arrays for file data //
if (Danfile == NULL)
{
printf ("ERROR\n");
}
else
{
printf("Everything works!\n");
fprintf (Danfile, "Welcome to Dan's file.");
fgets(fileinfo,50,Danfile);
printf("%s\n",fileinfo);
fclose (Danfile); // CLOSES FILE //
}
return 0;
}
Since you're both reading and writing from the file you want to use "w+" to open the file rather than just "w".
But that won't fix things because once you've written out that text, your position in the file is still at the end, so you'll also need to reset the position before you can read anything in using fseek()
fseek(Danfile,0,SEEK_SET);
While using fopen() you pass the option for opening as an argument to the funtion. Here is the list:
"r" - Opens the file for reading. The file must exist.
"w" - Creates an empty file for writing. If a file with the same name already exists,
its content is erased and the file is considered as a new empty file.
"a" - Appends to a file. Writing operations, append data at the end of the
file. The file is created if it does not exist.
"r+" - Opens a file to update both reading and writing. The file must exist.
"w+" - Creates an empty file for both reading and writing.
"a+" - Opens a file for reading and appending.
Try using "r+" or "w+". After writing some text, your position in the file will move forward along with the text. Use rewind(FILE* filename) to move your position straight to the start of the file. For more information related to file handling i recommend checking what is inside stdio library:
https://www.tutorialspoint.com/c_standard_library/stdio_h.htm
So, I have this function on my program that is supposed to save a "car_str" structure into the desired place on a file specified as a parameter. But when I run it, it keeps overwriting the first slot again and again, as if fseek didn't point to the specified place on the file. Is there any problem with my code? I think it may be related with the multiplication, since without it the program does well, but I cannot point to the place I want.
void save(int car_nbr)
{
FILE *f;
f = fopen("memory.txt","wb");
if (!f)
{
printf ("error");
}
else
{
car_nbr--;
fseek(f, sizeof(struct car_str)*car_nbr, SEEK_SET);
fwrite(&car,sizeof(struct car_str),1,f);
rewind(f);
fclose(f);
printf("\nsaved");
}
}
you need to fopen with r+b.
if you fail than file not exist, so you can try use "wb"
"w" - write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
"r+" - read/update: Open a file for update (both for input and output). The file must exist.
f = fopen("memory.txt","r+b");
Hi I'm trying not to overwrite a file in C using fopen(file, "w");
My question is the file already exists as a 10 MB file but when I used the fopen the file ends up becoming 1KB. I want to write something to the file but I want it to stay the same size as well. How would I accomplish this? I saw that the "a+" appends things to the end of the file but what if I want to write something to the beginning of the file without expanding the size? It's just an empty file
Alternatively, is there a way to create a file in C with a certain size (such as 10MB)?
Yes, it is possible. By opening it with r+ you open it for 'reading and writing' (while w opens it for writing freshly).
Regarding your other question: Open a file with w and write 1000 1024 byte blocks to the file like this:
FILE *fp = fopen("file", "wb");
if(fp) {
int i = 0;
char Buf[1024];
for(; i < 1000; ++i)
fwrite(Buf, 1, 1024, fp);
fclose(fp);
}
Just once more the fopen flags for you:
r -> Opens file for reading. (File remains unchanged)
w -> Opens file for writing. (File gets erased)
a -> Opens file for appending. (File remains unchanged, file pointer gets moved to end)
Aside from these three main types, you can add a few more additional options:
b -> Opens the file as binary, ignoring formatting characters like \n
t -> Opens the file as text, specifically parsing \n as \r\n under Windows.
Open the file, then use fseek to set your position to the beginning of your file.
Edit: use r+ mode when opening. From man fopen:
r+ Open for reading and writing. The stream is positioned at
the beginning of the file.
*a way to create a file in C with a certain size (such as 10MB)?
like this:
#include <stdio.h>
int main(void){
const char *TenMBfile = "TenMB";
FILE *fp;
fp=fopen(TenMBfile, "w");
fseek(fp, 10*1024*1024-1,SEEK_SET);
fputc(0, fp);
fclose(fp);
return 0;
}
Hye! I worked on a project for adding text or 'blog' post on my web page and I found a pretty cool way to do it.
For this, I'll use a HTML file and my program.
HTML FILE:
<html>
<body>
<p> Hey this is the asssdsadasdsadas paragraph</p><br>
<p> Hey this is the asssdsadasdsadas paragraph</p><br>
</body>
</html>
C FILE:
printf("Please enter the number of bytes to write from in %s .\n", argv[0]);
int offset;
scanf("%d", &offset);
fseek(fp, -offset, SEEK_END);
strcat(argv[1], "<br>\n\n");
fprintf(fp, "%s", argv[1]);
fprintf(fp, "</body>\n</html>\n");
HTML explanation:
I start with one line defined
I put a blank line which I am going to write there.
Then I got all my ending tags.
C explanation:
I ask how many bytes I want to seek from the ending of the file wich is 17 in this case(to write to the blank line).
I get the number with scanf()
Then I seek in the file at minus x bytes because normally it's going to add bytes and we specify the whence.
Then for the purpose, here I add a break tag and also 2 newline to continue the cycle.
Then I write my wanted text.
Last, I add my 2 last tags, because when I write my text, it overwrites all after it. So after, the cursor is positioned after the last newline and I can write the ending tags.
So... This is how you can do it.
This question already has answers here:
How to truncate a file in C?
(6 answers)
Closed 8 years ago.
I am using fopen fseeko64 ftello64 fclose etc. to operating on a file.
How can I truncate a file? I know that there is no standard way to do this in C. All I want is some way that will work on any win32 platform. I'm using mingw gcc to compile.
Please note: I meant truncate the size of the file to a specified size, not make it 0 size. And using a trick like copy part to another file and delete/rename is not appropriate.
SetEndOfFile()
Get a handle to the file with write access, set the file pointer, then call SetEndOfFile().
-Adam
If you want to truncate the file to zero size, you can fopen with the "w" flag:
FILE *fh = fopen("file.txt","w");
if (fh != NULL) fclose(fh);
For truncating to a specific size in standard C, you can do this with a transfer/rename solution, something like:
FILE *finp = fopen ("inp.txt", "rb"); // should check for NULLs
FILE *fout = fopen ("out.txt", "wb");
size_t sz = 100000; // 100,000 bytes
char *buff = malloc (sz); // should check for NULL
sz = fread (buff, 1, sz, fin); // should check for errors
fwrite (buff, 1, sz, fout);
free (buff);
fclose (fin);
fclose (fout);
rename ("out.txt", "inp.txt); // should check for error
Of course, if you have access to the Win32 headers and libraries (and I believe MinGW gives you this), you can use SetEndOfFile(), since it does it in place, rather than having to create a new file and then rename it.
That means using Windows handle-based file I/O rather than the C FILE*-based but, if you're limiting yourself to Windows anyway, that may not matter. If you want portability on the other hand, you'll need a solution based on standard C, such as the transfer/rename solution above.
For FILE based file operations, use _fileno() and _chsize_s() to change the size of a file.
int changesize(FILE *fp, __int64 size)
{
int filedes = _fileno(fp);
return _chsize_s(filedes, size);
}
A truncate version can be written by validating that the supplied size is less than the current file size, as _chsize_s() will truncate or extend a file's size - see http://msdn.microsoft.com/en-us/library/whx354w1(VS.80).aspx.
If you simply fopen() a file with the "w" argument, it will be truncated.
http://www.cplusplus.com/reference/clibrary/cstdio/fopen.html
As mentioned already, you can use fopen() with the "w" flag like:
FILE *f = fopen("file.txt", "w");
Also, if you already have the file opened, you can use the function freopen(), again with the "w" flag:
FILE *f = fopen("file.txt", "r"); //initial fopen() call
...
f = freopen("file.txt", "w", f); //reopens "file.txt" and truncates it
http://www.cplusplus.com/reference/clibrary/cstdio/freopen.html
EDIT: After seeing you've edited your OP, I won't repost what Pax and Adam Davis has already put. Also, I'll confirm what Pax said, that the MinGW does give you access to the Win32 headers.