Write to .txt file? - c

How can I write a little piece of text into a .txt file?
I've been Googling for over 3-4 hours, but can't find out how to do it.
fwrite(); has so many arguments, and I don't know how to use it.
What's the easiest function to use when you only want to write a name and a few numbers to a .txt file?
char name;
int number;
FILE *f;
f = fopen("contacts.pcl", "a");
printf("\nNew contact name: ");
scanf("%s", &name);
printf("New contact number: ");
scanf("%i", &number);
fprintf(f, "%c\n[ %d ]\n\n", name, number);
fclose(f);

FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);
/* print integers and floats */
int i = 1;
float pi= 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, pi);
/* printing single characters */
char c = 'A';
fprintf(f, "A character: %c\n", c);
fclose(f);

FILE *fp;
char* str = "string";
int x = 10;
fp=fopen("test.txt", "w");
if(fp == NULL)
exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);

Well, you need to first get a good book on C and understand the language.
FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);

Related

fprintf places in odd value when processing char value

I am writing what should be a simple program, but I'm having an odd issue with fprintf I have not been able to solve.
I am reading a small CSV text file and writing those values to a separate file containing only the numeric values.
My CSV file looks like this.
000,001,002,
003,004,005,
006,007,008,
009,010,011,
255,255,255
There is a comma between each value and a return at the end of each line.
The code I am using is
#include <stdio.h>
#include <string.h>
int main(int argc, char ** argv) {
FILE * inputFile;
FILE * outFile;
char * filename;
int records = 0;
char line[15];
char * sp;
char appendString[] = ".hex";
printf("useage: dec2hex inputFile.txt\n");
// Check if a filename has been specified in the command
if (argc < 2) {
printf("Missing Filename\n");
return (1);
} else {
filename = argv[1];
printf("Read in Filename : %s\n", filename);
}
// Open file in read-only mode
inputFile = fopen(filename, "r");
if (inputFile == NULL) {
printf("Hey! Failed to open the file\n");
return (1);
}
strcat(filename, appendString);
printf("write out filename : %s\n", filename);
outFile = fopen(filename, "w");
while (fgets(line, 15, inputFile) != NULL) {
sp = strtok(line, ",");
char Y_pos = atoi(sp);
sp = strtok(NULL, ",");
char X_pos = atoi(sp);
sp = strtok(NULL, ",");
char OType = atoi(sp);
//print to file
fprintf(outFile, "%c", Y_pos);
fprintf(outFile, "%c", X_pos);
fprintf(outFile, "%c", OType);
records++;
}
fprintf(outFile, '\0');
printf("records = %d\n", records);
fclose(inputFile);
fclose(outFile);
return (0);
}
This will write to a file ..hex
The output I'm expecting should be
000102030405060708090a0bffffff
However what I'm seeing is an odd value inserted $D0.
I'm expecting $0A which does happen afterwards. I have tried some other values in my CSV (from 0 to 50) and this for now seems to be the only value that is random.
The reason I'm using %c in my fprintf is that I only need values from 0-255.
My first question, is why the odd value when processing 010?
How can this be corrected?
I'm using the TCC compiler 0.9.26, but have gotten similar results when using VS.
Thanks
However what I'm seeing is an odd value inserted $D0 $0D.
File was opening in text mode and when writing a code 10 ('\n'), incurred a "\n" to "\r\n" translation on OP's machine.
Instead open the file in binary mode.
// outFile = fopen(filename, "w");
outFile = fopen(filename, "wb");
Note: Other code short-comings exist.
you do not this strtok and atoi magic or binary mode opening magic
int main(void)
{
char line[1000];
while (fgets(line, 100, stdin) != NULL)
{
int X,Y,O;
if(sscanf(line, "%d,%d,%d,", &Y, &X, &O) != 3) { /* error handling*/ }
else
{
printf("%02x ", Y);
printf("%02x ", X);
printf("%02x ", O);
}
}
}
https://godbolt.org/z/vvKGzdcvd

Print data of a file stored in file pointer in C

I have written content to a file using a file pointer. I would now like to print this data in the form of an array. I am new to programming in C, and it looks like printing file pointers is different.
Here is an example of my code,
int main(){
double a=0;
double b=0;
double c=0;
double d=0;
int bufferLength = 330752;
char buffer[bufferLength];
FILE *fp = fopen("original.dat", "r");
if (!fp){
printf("Cant open the original file\n");
return -1;
}
FILE *fp1 = fopen("24bitnoise.dat", "r");
if (!fp1){
printf("Cant open the noise file\n");
return -1;
}
FILE *outfp= fopen("out.dat", "w");
if(outfp == NULL)
{
printf("Unable to create file\n");
}
while(fgets(buffer, bufferLength, fp)) {
if (2==sscanf(buffer, "%lf %lf", &a,&b)){ // Just printing col 2 //
// printf("b: %f\n", b);
fprintf(outfp, "%0.25f\n", b);
}
}
FILE *noisefp= fopen("outnoise.dat", "w");
if(noisefp == NULL)
{
printf("Unable to create file\n");
}
while(fgets(buffer, bufferLength, fp1)) {
if (2==sscanf(buffer, "%lf %lf", &c,&d)){ // Just printing col 2 //
fprintf(noisefp, "%0.25f\n", d);
}
}
printf("%f", outfp);
printf("File transferred\n");
fclose(outfp);
fclose(fp);
fclose(fp1);
fclose(noisefp);
return 0;
}
I would now like to print the values from *outfp in the form of an array.
OP is attempting, incorrectly, to print the contents of a file with
printf("%f", outfp);
"%f" expects a matching double, not a FILE *.
To print the text contents of a file, line-by-line:
FILE *inf = fopen("out.dat", "r");
if (inf) {
while(fgets(buffer, bufferLength, inf)) {
printf("%s", buffer);
}
fclose(inf);
}
how can I put these values into an array?
The "trick" is how to determine the size of the array.
One simple approach:
size_t count = 0;
while(fgets(buffer, bufferLength, fp)) {
if (2==sscanf(buffer, "%lf %lf", &a,&b)) {
count++;
}
}
double fp_array = malloc(sizeof *fp_array * count);
if (fp_array == NULL) Handle_Out_of_memory(); // Some tbd code
// Read again
rewind(fp);
size_t i = 0;
while(fgets(buffer, bufferLength, fp)) {
if (2==sscanf(buffer, "%lf %lf", &a,&b)) {
fp_array[i++] = b;
}
}
// Use fp_array
free(fp_array); // clean up when done.
A more elegant approach would re-size the allocation as needed and perform only one read pass.

How to store string to txt file

void inserting()
{
char file_name[50];
char sentence[1000];
FILE *fptr;
printf("File name (With extn):");
scanf("%s", file_name);
fptr = fopen(file_name, "a");
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
scanf("%s", sentence);
fgets(sentence,sizeof(sentence),stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
}
I want to store content from string to file... but it is displaying everything except the first word..
INPUT : Hello this is C program //which I have entered
OUTPUT: this is C program //this is what stored in file
#include<stdio.h>
void inserting()
{
char file_name[50]="C:\\Users\\Dev Parzival\\Desktop\\foo.txt";
char sentence[1000];
FILE *fptr;
//printf("File name (With extn):");
//scanf("%s", file_name);
fptr = fopen(file_name, "w");
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
scanf("%[^\n]", sentence);
printf(sentence);
//fgets(sentence,sizeof(sentence),stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
}
int main(){
inserting();
}
scan will not read spaces with%s u have to include spaces also I assume thats why use %[^\n]format specifier.
If you want to preserve your code make the adjustment
void inserting(){
char file_name[50];
char sentence[1000];
FILE *fptr;
printf("File name (With extn):");
scanf("%s", file_name);
fptr = fopen(file_name, "a");
if (fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
scanf("%s", sentence);
fprintf(fptr,"%s",sentence); //<-- HERE
fgets(sentence,sizeof(sentence),stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
}
Or you can use something like getline just to be cleaner.

trying to save data that is in an array to a file

This is my attempt at saving to a file. Once I enter the filename, it will save a file with that name, but it does not print anything to it and I dont get why.
if (menuoption == 6)
{
printf("please enter a file name\n");
scanf("%s", filename);
filepointer = fopen(filename, "a");
if (filepointer == NULL);
{
printf("unable to open file name: %s\n", filename);
continue;
}
fprintf(filepointer, "decimal values:");
for (int i = 0; i < doubcount; i++)
{
fprintf(filepointer, "%lf \n", doubles[i]);
}
fprintf(filepointer, "\n");
fprintf(filepointer, "integer values: ");
for (int i = 0; i < intcount; i++)
{
fprintf(filepointer, "%d\n", ints[i]);
}
fprintf(filepointer, "\n");
}
Here a sample I just wrote to show you how you should handle files in C
#include <stdio.h>
int main(void){
char* filename;
FILE* fp;
printf("Enter a file name:\n");
scanf("%s", filename);
fp = fopen(filename, "w");
if(fp == NULL){
fprintf(stderr, "unable to open file name: %s\n", filename);
return -1;
}
fprintf(fp, "Testing\n");
fclose(fp);
}
First of all, you should use "w" instead of "a" in fopen function
fp = fopen(filename, "w");
You can read about the modes you can open a file here http://man7.org/linux/man-pages/man3/fopen.3.html
Then you should always close a file after reading or writing it, so add this line to your code
fclose(fp);
I hope this can work for your, unfortunately I couldn't run your code, because it lacks of variable declarations, includes and all other stuff

End of File occurs when reading char 0x1A

I am trying to read a file with around 1000 characters in it. The file reading terminates when an 0x1A character is encountered. I want that:
0x1A should not terminate the reading.
0x1A should be stored like a normal character.
Can I use an alternate method of reading the file, maybe?
int main(void)
{
int x=0,ch = ' ', file_name[25], arr[1000];
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
fp = fopen(file_name, "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name); getchar();
int y= 0;
while ((ch = fgetc(fp)) != EOF)
{
printf("%d) %x \n",y, ch);
arr[y++] = ch;
printf(" %x \n", arr[(y- 1)]);
}
printf("Press to see the data off array..."); getchar();
for (int x = 0; x < y; x++)
{
printf("%d ", (x + 1));
printf(". %x \n", arr[x]);
}
getchar();
fclose(fp);
return(0);
}
You opened the file as txt mode,
fp = fopen(file_name, "r"); // txt mode
Please try binary mode to read 0x1A,like
fp = fopen(file_name, "rb"); // binary mode
Instead of fgetc() you can use fgets .
while ((ch = fgetc(fp)) != EOF)
{
printf("%d) %x \n",y, ch);
payload[y++] = ch;
printf(" %x \n", arr[(y- 1)]);
}
you can simply write this using fgets()-
#define MAX 1024
//open file in "r" mode
char arr[MAX];
while(fgets(arr,MAX,fp))
{
printf("%s",arr);
}
Content in you file is stored in array arr.
While using fgets you don't have to worry about EOF as fgets itself return as it encounters EOF.

Resources