I have a similar code.
#include <stdio.h>
int main() {
FILE* file = fopen("file.txt", "w+");
fputc('A', file);
fflush(file);
char buff;
fscanf(file, "%s", &buff);
printf("read data: %s", &buff);
fclose(file);
return 0;
}
I want without close file read written data. But in buff not exist data.
Why?
If i close file after writing and then read all worked.
You should use rewind(file) to set the position indicator associated with the file stream to the beginning of the file.
Your example, working fine:
#include <stdio.h>
int main() {
FILE* file = fopen("file.txt", "w+");
fputc('A', file);
fflush(file);
rewind (file);
char buff [80];
fscanf(file, "%s", buff);
printf("read data: %s", buff);
fclose(file);
return 0;
}
Rewind back to the beginning of the file:
rewind(file);
Related
I am trying to XOR a file. I read in the file which consists of 1 line of text "this is some random text". When I perform the XOR operation I then output the XORed file which contains the value 00. When I XOR the file again and output the contents all that is in the file is "this is s". I am new to all of this so any information is helpful. I am planing on using this for .exe files and I am curious as to if this is successful for .txt files will it also work for .exe
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
//XOR key
#define XOR_KEY 0x6F
void XORFile (char *infile, char *outfile){
FILE *fp;
char buf[4096];
fp = fopen (infile, "r");
fgets (buf, sizeof (buf), fp); //Reading from file
printf ("File contents: %s\n", buf);
int i;
//XOR read file buffer
for(i = 0; buf[i] != '\0'; i++){
buf[i] ^= XOR_KEY;
}
FILE *fp2;
fp2 = fopen (outfile, "w");
fprintf (fp2, "%s", buf);
fclose(fp);
fclose (fp2);
}
int main (int argc, char *argv[]) {
if(argc <= 3){
fprintf (stderr, "Usage: %s [CRYPT] [IN FILE] [OUTFILE]\n", argv[0]);
exit(1);
}
XORFile (argv[2], argv[3]);
return 0;
}
You want to use fread instead of fgets. You need to treat the input and output as binary.
And, you want to loop on it to get the entire file.
As it is, you'll only get the first line.
This seems like encrypt/decrypt. Even if you looped on fgets, it will not work for the decrypt because the newline will have been XORed and won't give desired results.
Here's a refactored version:
void
XORFile(char *infile, char *outfile)
{
FILE *fp;
FILE *fp2;
int rlen;
char buf[4096];
fp = fopen(infile, "r");
fp2 = fopen(outfile, "w");
while (1) {
rlen = fread(buf,1,sizeof(buf),fp);
if (rlen <= 0)
break;
// XOR read file buffer
for (int i = 0; i < rlen; ++i)
buf[i] ^= XOR_KEY;
fwrite(buf,1,rlen,fp2);
}
fclose(fp);
fclose(fp2);
}
How can I write and create the file, append if the file exists, then display all string file text? I can't append the content to at the end of file text, then display all strings. Thank for reading!
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<unistd.h>
int main(int argc, char** argv) {
char c, filename[100], content[100];
FILE *fptr;
printf("File name: ");
scanf("%s", filename);
printf("Enter content: ");
gets(content);
if ((fptr = fopen(filename, "r")) == NULL)
{
fptr = fopen(fptr, "w");
fprintf(fptr,"%s", content);
}
else{
fptr = fopen(fptr, "a");
fprintf(fptr,"%s", content);
}
c = fgetc(fptr);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fptr);
}
fclose(fptr);
return 0;
}
If you want to open a file for reading and to also append to it, you can do that with just one call to fopen by using the mode a+.
fptr = fopen(filename, "a+");
if (fptr == NULL)
{
// Handle not being able to open the file
}
If the file doesn't exist, it will create it. The position for reading will be at the beginning of the file, but anything you write to it will be at the end.
There are lot of bugs as mentioned by others in comments. I tried to explain in comments, read it carefully.
int main(int argc, char** argv) {
char filename[100], content[100];
FILE *fptr;
printf("Enter content: \n");
fgets(content,sizeof(content),stdin); /*use fgets() instead of gets()*/
printf("File name: ");
scanf("%s", filename);
if ((fptr = fopen(filename, "r")) == NULL) {/*if doesn't exist */
fptr = fopen(filename, "w"); /*create it */
fprintf(fptr,"%s", content); /* and write it */
}
else{
/* it should be a+ if you want to read, as you are doing using fgetc() */
fptr = fopen(filename, "a+");/*if exist, write at end of file */
fprintf(fptr,"%s", content);/* write at end */
}
rewind(fptr);/* move the fptr to beginning to read further */
int c = 0; /* fgetc() returns integer */
while( (c = fgetc(fptr))!= EOF) {
printf ("%c\n", c);
}
fclose(fptr);
return 0;
}
Use fgets() instead of gets(). Read here Why is the gets function so dangerous that it should not be used?
What I want to do for now is have an input text file, load its content into a 2d array, perform something on it and then put it out into another file. Essential problem for me is keeping the original files' structure. This is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *ifp, *ofp;
char buffer[100];
int i, c;
ifp=fopen("test.in", "r");
ofp=fopen("test.out", "w");
while (!feof(ifp)){
if(fscanf(ifp, "%s", buffer) != 1)
break;
fprintf(ofp, "%s", buffer);
}
return 0;
}
my input:
aaa bb bbb
bbbbb bbbb aa
and output:
aaabbbbbbbbbbbbbbaa
Everything I tried for EOL or EOF recognition caused infinite loops. Performing anything with "%c" instead of "%s" resulted in worse outputs. Thanks in advance.
edit: I'm aware I can get the output to be words with spaces between them or have every word in a new line but I don't know how to get from here to final result.
Use "%c"
#include <stdio.h>
int main(void)
{
FILE *ifp, *ofp;
char buffer;
ifp=fopen("test.in", "r");
if(ifp==NULL)return 1;
ofp=fopen("test.out", "w");
if(ofp==NULL){
fclose(ifp);
return 1;
}
for(;;){
if(fscanf(ifp, "%c", &buffer) != 1)
break;
fprintf(ofp, "%c", buffer);
}
fclose(ifp);
fclose(ofp);
return 0;
}
or getc().
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *ifp, *ofp;
int buffer;
ifp=fopen("test.in", "r");
if(ifp==NULL)return 1;
ofp=fopen("test.out", "w");
if(ofp==NULL){
fclose(ifp);
return 1;
}
for(;;){
if((buffer = getc(ifp)) != EOF)
break;
putc(buffer, ofp);
}
fclose(ifp);
fclose(ofp);
return 0;
}
You won't neeed feof() because the functions used to read will detect EOF.
Also, don't forget to check if the files are successfully opened and to close the files opened.
Use getline function instead fscanf. Because fscanf can't read the full string which contain the space character
while ((read = getline(&line, &len, stream)) != -1)
{
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
See full detail about getline:
http://man7.org/linux/man-pages/man3/getline.3.html
I am reading a text file and trying to display its contents on the console. Here is my code:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <fstream>
int main()
{
FILE* fp=NULL;
char buff[100];
fp=fopen("myfile.txt","r");
if(fp==NULL)
{
printf("Couldn't Open the File!!!\n");
}
fseek(fp, 0, SEEK_END);
size_t file_size = ftell(fp);
fread(buff,file_size,1,fp);
printf("Data Read [%s]",buff);
fclose(fp);
return 0;
}
but only redundant data is being displayed on the console; could someone please point out my mistake?
You forgot to reset the file pointer to start after doing this.
fseek(fp, 0, SEEK_END);
Do this after finding size (file_size).
rewind (fp);
You need to seek back to the start of the file before reading:
int main()
{
FILE* fp=NULL;
char buff[100];
fp=fopen("myfile.txt","r");
if(fp==NULL)
{
printf("Couldn't Open the File!!!\n");
exit(1); // <<< handle fopen failure
}
fseek(fp, 0, SEEK_END);
size_t file_size = ftell(fp);
fseek(fp, 0, SEEK_SET); // <<< seek to start of file
fread(buff,file_size,1,fp);
printf("Data Read [%s]",buff);
fclose(fp);
return 0;
}
Try it....
#include <stdio.h>
#include <stdlib.h>
void handle_line(char *line) {
printf("%s", line);
}
int main(int argc, char *argv[]) {
int size = 1024, pos;
int c;
char *buffer = (char *)malloc(size);
FILE *f = fopen("myfile.txt", "r");
if(f) {
do { // read all lines in file
pos = 0;
do{ // read one line
c = fgetc(f);
if(c != EOF) buffer[pos++] = (char)c;
if(pos >= size - 1) { // increase buffer length - leave room for 0
size *=2;
buffer = (char*)realloc(buffer, size);
}
}while(c != EOF && c != '\n');
buffer[pos] = 0;
// line is now in buffer
handle_line(buffer);
} while(c != EOF);
fclose(f);
}
free(buffer);
return 0;
}
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <fstream>
int main()
{
FILE* fp=NULL;
char *buff; //change array to pointer
fp=fopen("myfile.txt","r");
if(fp==NULL)
{
printf("Couldn't Open the File!!!\n");
}
fseek(fp, 0, SEEK_END);
size_t file_size = ftell(fp);
buff = malloc(file_size); //allocating memory needed for reading file data
fseek(fp,0,SEEK_SET); //changing fp to point start of file data
fread(buff,file_size,1,fp);
printf("Data Read [%s]",buff);
fclose(fp);
return 0;
}
having a buffer of 100 bytes to read a file is not a better idea as since the file size may be more than 100 bytes.
A better file io can be done by doing a fgets on the file, if its not a type of metadata that you wanted to read using the fread.
fgets in a while loop can be used to check whether its reached EOF or a feof call can be used to check the EOF.
a sample code listing of fgets can be like this:
while (fgets(buf, len, fp)) {
printf("%s", buf);
}
or a sample that is used with fgets can be like this:
while (fread(buf, len, 1, fp) >= 0) {
printf("%s\n", buf);
}
I have one text file. I have to read one string from the text file. I am using c code. can any body help ?
Use fgets to read string from files in C.
Something like:
#include <stdio.h>
#define BUZZ_SIZE 1024
int main(int argc, char **argv)
{
char buff[BUZZ_SIZE];
FILE *f = fopen("f.txt", "r");
fgets(buff, BUZZ_SIZE, f);
printf("String read: %s\n", buff);
fclose(f);
return 0;
}
Security checks avoided for simplicity.
This should work, it will read a whole line (it's not quite clear what you mean by "string"):
#include <stdio.h>
#include <stdlib.h>
int read_line(FILE *in, char *buffer, size_t max)
{
return fgets(buffer, max, in) == buffer;
}
int main(void)
{
FILE *in;
if((in = fopen("foo.txt", "rt")) != NULL)
{
char line[256];
if(read_line(in, line, sizeof line))
printf("read '%s' OK", line);
else
printf("read error\n");
fclose(in);
}
return EXIT_SUCCESS;
}
The return value is 1 if all went well, 0 on error.
Since this uses a plain fgets(), it will retain the '\n' line feed at the end of the line (if present).
void read_file(char string[60])
{
FILE *fp;
char filename[20];
printf("File to open: \n", &filename );
gets(filename);
fp = fopen(filename, "r"); /* open file for input */
if (fp) /* If no error occurred while opening file */
{ /* input the data from the file. */
fgets(string, 60, fp); /* read the name from the file */
string[strlen(string)] = '\0';
printf("The name read from the file is %s.\n", string );
}
else /* If error occurred, display message. */
{
printf("An error occurred while opening the file.\n");
}
fclose(fp); /* close the input file */
}
This is a Simple way to get the string from file.
#include<stdio.h>
#include<stdlib.h>
#define SIZE 2048
int main(){
char read_el[SIZE];
FILE *fp=fopen("Sample.txt", "r");
if(fp == NULL){
printf("File Opening Error!!");
}
while (fgets(read_el, SIZE, fp) != NULL)
printf(" %s ", read_el);
fclose(fp);
return 0;
}