C - Can't Create/Write to Files in VS2017 - c

Question Edited
i'm giving a bit of a background on my problem hoping that'll help you understand it better:
I've recently updated my IDE to VC++ 2017 . I've written a basic assembler (for mips ISA) as part of my studies.
All worked well till i've reached the final part of printing the memory image to text file - i've noticed that altough the file pointer was allocated with a value(not NULL) after using "fopen", nothing was written to it.
Here is the definition and the opening of the input/output files(out of context since lack of space);
//File Pointers
FILE *fp_mem = NULL, *fp_asm = NULL;
/** Entering Main Function **/
// open files
fp_asm = fopen(argv[2], "r");
fp_mem = fopen(argv[1], "w");
if (fp_asm == NULL || fp_mem == NULL)
{
perror("ERROR");
exit(errno);
}
/** Assembler functionality **/
//write to file loop
for (i = 0; i <= highest_mem_access && i < MEM_SIZE; i++)
{
int temp = fprintf(fp_mem, "%08X\n", mem[i]);
}
//free label memory
free_label_list();
fclose(fp_asm);
fclose(fp_mem);
I tried various options instead of fpritnf - didn't work.
Most importantly - No File is created in my project directory!
Any idea guys? i'm pretty hopeless... I'll share more of my code if needed.
EDIT
This is a simple try to write to files in VS2015:
#include <stdio.h>
int main()
{
//FILE *fp = fopen("C:/Users/Tom/Desktop/test.txt", "w");
FILE *fp = fopen("test", "w");
if (fp == 0)
{
perror("ERR");
return(11);
}
int count = fprintf(fp,"Hello there,General Kenobi");
fclose(fp);
}
fp isn't NULL , Count = 26 after fprintf , No file located anywhere.
I also tried to write to another location(in comment) - same issue.

Related

Is opening and closing the same file multiple times a bad practice in C?

my C program does 3 things:
reads from a text file
converts all letters into upper-case
prints the converted text into the console.
Here are how many times I'm opening and closing those 2 files in my program:
Original => 1 for "r"
New => 2 first for "w+" and last for "r"
Is there a better way to write to a file and read from it without opening and closing a multiple times? (even though I only opened and closed twice, I wanna build a good practice)
#include <stdio.h>
#include <ctype.h>
int main()
{
const char ORIGINAL[] = "challenge2.txt";
FILE *fp = NULL;
FILE *fpNew = NULL;
char ch, ch2;
///////////// open the original txt file to read /////////////
fp = fopen(ORIGINAL, "r");
if (fp == NULL)
{
perror("Error opening the file");
return (-1);
}
///////////// create and write on a new file /////////////
fpNew = fopen("challenge2_copy.txt", "w+");
printf("\n============== Original text ==============\n");
while ((ch = fgetc(fp)) != EOF)
{
printf("%c", ch);
ch = toupper(ch);
fputc(ch, fpNew);
}
fclose(fp);
fp = NULL;
fclose(fpNew);
fpNew = NULL;
///////////// call the new file to print the converted text /////////////
fpNew = fopen("challenge2_copy.txt", "r");
if (fpNew == NULL)
{
perror("Error opening the file");
return (-1);
}
printf("\n============== Converted to Uppercase ==============\n");
while ((ch2 = fgetc(fpNew)) != EOF)
{
printf("%c", ch2);
}
fclose(fpNew);
fpNew = NULL;
return 0;
}
Here's the console output:
============== Original text ==============
hello I AM JACK
I AM TESTING lowerCASE
GONNA convert THIS into
UPPERcase
i hope THIS works
============== Converted to Uppercase ==============
HELLO I AM JACK
I AM TESTING LOWERCASE
GONNA CONVERT THIS INTO
UPPERCASE
I HOPE THIS WORKS
Good practices, performance, dangers.
MS Visual Studio suggest using fopen_s as good practise :)
Sometimes reopening file sometimes makes code more clear to read in big projects.
As for performance, it will take some time for processor to make new FILE instance and fill it with all file properties.
There can also be some interrupts eg. after releasing ownership for a while cloud sync. tools may want to back up newly created file and will block accessing it for other apps. (your program).
Performance solution.
So as to reuse a FILE instance you need only to jump into different place in FILE buffer (eg. start of the file).
You can achieve it with fsetpos or fseek functions from stdio.h.
https://www.cplusplus.com/reference/cstdio/fsetpos/
https://www.cplusplus.com/reference/cstdio/fseek/
Example FILE instance reusage.
/* fsetpos example */
#include <stdio.h>
int main ()
{
FILE * pFile; fpos_t position;
#define buffSize 1024 //1KB
char s[buffSize];
//Write
pFile = fopen ("myfile.txt","w+");
fgetpos (pFile, &position);
fputs ("That is a sample",pFile);
//Reuse for reading
fsetpos (pFile, &position);
puts (fgets(s,buffSize, pFile));
//Next reuse for reading
fsetpos (pFile, &position);
puts (fgets(s,buffSize, pFile));
fclose (pFile);
return 0;
}
The above code produces the following result:
That is a sample
That is a sample

fopen() doesn't work, despite the file clearly existing

When running my C code on WSL (ubuntu), I'm attempting to use fopen() on a file that 100%, positively, absolutely exists. And yet, it keeps saying that it doesn't exist despite it 100%, positively, absolutely existing.
int main (int argc, char *argv[]) {
char *path = "/bin/";
char *line;
// runs batch mode (tests use this mode)
if (argc == 2) {
char *line;
FILE *fp;
for (int i = 0; i < strlen(argv[1]); i++) {
if (argv[1][i] == '\n') {
argv[1][i] == '\0';
}
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
perror("fopen");
}
I'm 100% certain that it's searching in the correct directory, because if I change the mode from "r" to "w", it creates a file with an identical name in the correct directory, right next to the file that already exists with the same name.
I'm seriously at the end of my rope. Absolutely none of this makes sense, especially how it doesn't pick up on there being duplicate files. Can someone please help?
Make certain your input file, that "exist" is not also used someplace else exclusively, like an editor.
Form a sibling file.
Example:
FILE *outf = fopen("test.txt", "w");
if (outf) {
fprintf(stderr, "<%s>\n", argv[1]);
fprintf(outf, "<%s>\n", argv[1]);
fclose(outf);
}
fp = fopen(argv[1], "r");
Was that test file located where you expected and with the expected contents?
Post that files contents.

Why my code does not write the results to the file?

I am writing a code that reads the characters from a file, and then if one of these characters is 'A' it should be changed to 'Z', after these changes are made it should write it back to the file (not append, but write), but whenever I open the file after running the code or it is empty, corrupted, or the compiler shouts at me (since I tried correcting it by making some changes, here is the code I have so far:
int main(){
char variable1[2000000];
FILE *filePointer1;
FILE *filePointer2;
int counter;
int exact_char_numb;
filePointer1 = fopen("File.txt", "r");
filePointer2 = fopen("File.txt", "w");
fread(variable1,2000000,sizeof(char), filePointer1);
for(counter = 0; counter<= 2000000 ; counter ++){
if(variable1[counter] == 'A'){
variable1[counter] = 'Z';
}
if(variable1[counter] == '+'){
exact_char_numb = counter; // I am using '+' to mark the end of
} // the file (for now)
}
fwrite(variable1,sizeof(char),exact_char_numb,filePointer2);
printf("%s\n", variable1);
printf("%d\n", exact_char_numb);
return 0;
}
In this call:
fwrite(variable1,sizeof(char),exact_char_numb,filePointer2);
the variable exact_char_numb is likely equal to zero, so you don't get any output. You should turn on all warnings and the compiler will complain to you about the variables that can be used without initializing them first.
"but whenever I open the file after running the code or it is empty, corrupted, or the compiler shouts at me..."
You should check whether the opening of the streams to file.txt were successful by checking the returned pointers for a null pointer before doing any operations with the streams:
if (!(filePointer1 = fopen("File.txt", "r")))
{
fputs("Error occurred at opening file to read!", stderr);
exit(1);
}
if (!(filePointer2 = fopen("File.txt", "w")))
{
fputs("Error occurred at opening file to write!\n", stderr);
exit(1);
}
Furthermore, you donĀ“t need to do have two pointers to two different streams. Use r+ mode:
if (!(filePointer = fopen("File.txt", "r+")))
{
fputs("Error occurred at opening file!", stderr);
exit(1);
}

Can't get fwrite to work properly

I'm trying to write a program that is able to open a text file and split it so I can save it in two new ones to save files faster. But with the code I have now I'm not able to print the chars that I pick from the orignal file to the new ones.
In my text file I have the text "Dutch people are tall".
In my new files I want to get:
File 1: Dthpol r tl
File 2: uc epeaeal
This is the code I have got so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char cUsb1;
char cUsb2;
char str[128];
FILE *ptr_readfile;
FILE *ptr_usb1;
FILE *ptr_usb2;
ptr_readfile = fopen("Dutch People.txt","r"); // open readfile
while(ptr_readfile != NULL) // keep running while readfile != null
{
if (ptr_readfile != EOF) // keep running while readfile != eof
{
cUsb1 = fgetc(ptr_readfile); // to get a char out of the readfile
ptr_usb1 = fopen("USB1.txt", "w"); // create and open USB1 file
fwrite(cUsb1 , str , str , ptr_usb1); //writing get c to file
cUsb2 = fgetc(ptr_readfile); // to get a char out of the readfile
ptr_usb2 = fopen("USB2.txt", "w"); // create and open USB2 file
fwrite(cUsb2 , str , str, ptr_usb2); //writing get c to file
fclose(ptr_usb1); // closing the file
fclose(ptr_usb2); // closing the file
}
break; // to stop the while loop
fclose(ptr_readfile); // closing the file
}
return 0;
}
Many things are not quite right. You need to look carefully through the warnings reported by the compiler - enable all warnings if possible (e.g. "-Wall") - and resolve them all. Then single-step through your program with a debugger until it does something you didn't expect.
As a starting point, instead of:
fwrite(cUsb1 , str , str , ptr_usb1);
you might mean
fwrite(&cUsb1 , 1 , 1 , ptr_usb1);
There should be a warning for that line to tell you that you shouldn't try to pass cUsb1 (a char) as the first parameter of fwrite, as that parameter expects a pointer, i.e. an address of something. Use &cUsb1 to mean "the address of cUsb1".
You can use fputc for writing one character at a time. Also the while loop is not needed.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c;
int i = 0;
FILE *ptr_readfile = NULL;
FILE *ptr_usb1 = NULL;
FILE *ptr_usb2 = NULL;
ptr_readfile = fopen("Dutch People.txt", "r"); // open readfile
if (ptr_readfile != NULL) {
ptr_usb1 = fopen("USB1.txt", "w"); // create and open USB1 file
ptr_usb2 = fopen("USB2.txt", "w"); // create and open USB2 file
if (ptr_usb1 != NULL && ptr_usb2 != NULL) {
while ((c = fgetc(ptr_readfile)) != EOF) {
if (i % 2 == 0) {
fputc(c, ptr_usb1);
}
else {
fputc(c, ptr_usb2);
}
i++;
}
}
fclose(ptr_readfile); // closing the file
}
if (ptr_usb1 != NULL) {
fclose(ptr_usb1);
}
if (ptr_usb2 != NULL) {
fclose(ptr_usb2);
}
return 0;
}

read text file in xcode

i tried to read text file in xcode but this
"EXC_BAD_ACCESS message showed up when i tried to build my program
here is my code
and i put inputA.txt file in the same folder with project file
my friend told me that i should put txt file in debug folder is this why i cannot read txt
file in this code? please help me...
macbook user.
int main (int argc, const char * argv[]) {
FILE* fp;
char mychar;
char arr[50][2] = {0, };
int i = 0;
int j, k;
graphType* G_;
G_ = (graphType*)malloc(sizeof(graphType));
Create(G_);
fp = fopen("inputA.txt", "r");
//fp = fopen("inputB.txt", "r");
//fp = fopen("inputC.txt", "r");
while(1){
for(j = 0 ; j < 2 ; j++){
mychar = fgetc(fp);
if(mychar == EOF)
break;
else if(mychar == ' ')
continue;
arr[i][j] = mychar;
}
i++;
}
Per default your binary will be generated in ProjectDir/build/Mode, with Mode being Debug or Release, and will have that as its working directory. If you want to refer to a file in the project directory, you'd have to use ../../input.txt in that case.
The build locations are configured in the "Build Locations" section in a targets or projects build tab. The working directory can be manually changed in the settings for the executable ("General", "Set the working directory to:") if needed.
If you are having doubts then you can always find out what the working directory is:
#include <unistd.h>
int main() {
char buf[2048];
getcwd(buf, sizeof(buf));
printf("%s", buf);
}
Most likely inputA.txt is not in the same file as the binary. You should make sure the text file is copied to the output directory in your project (whether manually or by hand).
Also, fopen will return NULL if the file couldn't be opened, so you might want to add a check for that.
if (fp == NULL)
{
printf("Could not open file!");
return 1;
}
fopen is probably returning null because your text file isn't in the right place. Don't forget to check for null!

Resources