Pelles C forum

C language => Beginner questions => Topic started by: John1 on June 02, 2019, 11:46:02 PM

Title: A File have not the expected content ?
Post by: John1 on June 02, 2019, 11:46:02 PM
Hello,

As I'am new to c and tried already to search on the web, I was thinking to ask here.

I'am trying to write a char Array to a File, but for some reasons the char seems empty.
I don't know if it depends on getting the Input or writing it to the the File.

I tried some different codes to write it to a File (it's not the whole code):


if(fgets(nVal,BUF,stdin) == NULL) {
  printf("Wrong Input\n");
} // Input for the Array

printf("%s",nVal); // printout as test, is empty

fp = fopen(DATAFILE,"w+"); // open the File

//for (int i = 0; i < sizeof (nVal) / sizeof(nVal); i++) {
  //fprintf(fp, "%s", nVal[i]);
//} // Test one, is empty

//if(fwrite(&nVal, sizeof(nVal), 1, fp) != 1) {
  //fprintf(stderr, "Write Error in %s\n", DATAFILE);
  //fclose(fp);
  //return;
//} // Test two, writes some random Stuff

fprintf(fp, "%s\n", nVal); // Test three, is empty


Where might be the Problem ?

Thanks
Title: Re: A File have not the expected content ?
Post by: TimoVJL on June 03, 2019, 08:45:42 AM
check errors in your code, try to delete file before running the program#include <stdio.h>

#define DATAFILE "test.txt"

int __cdecl main(int argc, char **argv)
{
FILE *fp;
fp = fopen(DATAFILE,"w+"); // "w+" Truncate to zero length or create text file for update.
if (fp) {
fprintf(fp, "%s\n", "row1");
fprintf(fp, "%s\n", "row2");
fclose(fp);
}
return 0;
}
Title: Re: A File have not the expected content ?
Post by: John1 on June 03, 2019, 10:23:06 AM
Hello TimoVJL,

Strange I can't find errors in the code.
Maybe I missunderstand something.


void addNewElement(void) {
FILE *fp;
char nVal[BUF];

if(fgets(nVal,BUF,stdin) == NULL) {
  printf("Wrong Input\n");
}

dump_buffer(stdin);
killNL(nVal);

fp = fopen(DATAFILE,"a+b");

if(fp == NULL) {
  printf("Error in open: %s\n", DATAFILE);
  exit(EXIT_FAILURE);
}
//for (int i = 0; i < sizeof (nVal) / sizeof(nVal); i++) {
  //fprintf(fp, "%s", nVal[i]);
//}
//if(fwrite(&nVal, sizeof(nVal), 1, fp) != 1) {
  //fprintf(stderr, "Error in writing in %s\n", DATAFILE);
  //fclose(fp);
  //return;
//}
fprintf(fp, "%s\n", nVal);
fclose(fp);
}

void dump_buffer(FILE *fp) {
int ch;
while((ch = fgetc(fp)) != EOF && ch != '\n'){}
}

void killNL(char *str) {
size_t p = strlen(str);
if(str[p-1] == '\n') {
  str[p-1] = '\0';
}
}
Title: Re: A File have not the expected content ?
Post by: John1 on June 10, 2019, 12:42:43 PM
Hello,

Thanks for your Answer.

The Problem was a Syntax Problem in the case Construct, which I didn't post, due there were no Errors in execution of the Program, which didn't see an obvious Problem. Just the Content of the File was not correct.

Have a good time
John