failing to dump the input file reversed - c

I want to reverse the contents of the input file and display the reversed contents, but I am not getting it; i think I have made a logic error.
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
int main() {
char* c = malloc(10);
char* c1 = malloc(10);
char ch, arg1[100], arg2[100];
int i, count = 0;
FILE *fp, *fq;
printf("Name of the file:");
scanf("%s", arg1);
fp = fopen(arg1, "w+");
if (!fp) {
perror("Failed to open file");
return errno;
}
printf("\t\t\t%s\n\n", arg1);
printf("\t\tInput the text into the file\n");
printf("\t\tPress Ctrl+d to the stop\n");
while ((*c=getchar()) != EOF) {
fwrite(c, 1, sizeof(c), fp);
count++;
}
printf("\n\n");
fclose(fp);
fp = fopen(arg1, "w+");
printf("Name of the output file:");
scanf("%s", arg2);
printf("Reversing the contents of the file.......\n");
fq = fopen(arg2, "w+");
printf("\t\t%s\n\n", arg2);
for (i = 1; i <= count; i++) {
fseek(fp, -(i + 1), SEEK_END)
fwrite(c1, 1, sizeof(c1), fq);
}
printf("Done....Opening the file\n");
rewind(fq);
for (i = 0; i <= count; i++) {
ch = getc(fp);
putc(ch, stdout);
}
fclose(fp);
fclose(fq);
return 0;
}

Here is an example program which loads the file into memory and then prints the content of the memory backwards to stdout.
#include <stdio.h>
#include <stdlib.h>
/* get the size of the file. No error checking here! */
long get_filesize(FILE *fp)
{
long fsize;
fseek(fp, 0, SEEK_END);
fsize = ftell(fp);
rewind(fp);
return fsize;
}
int main(int argc, char *argv[])
{
if(argv[1] == NULL) return EXIT_FAILURE;
FILE *input;
unsigned char *data;
long filesize;
int i;
/* open target file */
input = fopen(argv[1], "rb");
if(input == NULL) exit(EXIT_FAILURE);
/* retrieve size of the file */
filesize = get_filesize(input);
if(filesize < 1) exit(EXIT_FAILURE);
/* allocate space for the file */
data = malloc(filesize * sizeof(unsigned char));
if(data == NULL) exit(EXIT_FAILURE);
/* read the file into buffer and close the file handle */
fread(data, filesize, sizeof(unsigned char), input);
fclose(input);
/* print the file content from end to beginning */
for(i = --filesize; i >= 0; --i)
putchar(data[i]);
/* free the data buffer memory */
free(data);
return EXIT_SUCCESS;
}
Input text:
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type
specimen book.
Output text:
.koob nemiceps epyt a ekam ot ti delbmarcs dna epyt fo yellag a koot retnirp
nwonknu na nehw ,s0051 eht ecnis reve txet ymmud dradnats s'yrtsudni eht neeb
sah muspI meroL .yrtsudni gnittesepyt dna gnitnirp eht fo txet ymmud ylpmis si
muspI meroL

Related

Reading a file in C on Linux

How do I read a file into a string on Linux in C?
I came up with some code, but it's not working, and idk why. fgetc() always returns -1.
The file structure is something like this
.:
Files/
main.c
makefile
./Files:
test
Contents of main.c:
#include <stdio.h>
int fileLength(const char filePath[]);
void readFile(const char filePath[], char* outString);
int main()
{
char fileContents[fileLength("Files/test")];
readFile("Files/test", &fileContents);
printf("DEBUG: Address of fileContents is 0x%x\n", &fileContents);
printf("File contents:\n%s\n", fileContents);
return 0;
}
int fileLength(const char filePath[])
{
//Open the file
FILE* file;
if ((file = fopen(filePath, "r")) == NULL)
{
printf("ERROR: File (%s) cannot be opened.\n", filePath);
return -1;
}
//Find the length
fseek(file, 0, SEEK_END);
return ftell(file);
}
void readFile(const char filePath[], char* outString)
{
FILE* file;
//File reading
printf("DEBUG: File path is %s\n", filePath);
if ((file = fopen(filePath, "r")) == NULL)
{
printf("ERROR: File (%s) cannot be opened.\n", filePath);
exit(1);
}
//Get length of file and allocate the according amount of memory
fseek(file, 0, SEEK_END);
int fileLength = ftell(file);
printf("DEBUG: File length is %i\n", fileLength);
//Allocate string
char fileContent[fileLength];
//Read file to string
printf("DEBUG: File contents as digits:\n");
for (int i = 0; i < fileLength; i++)
{
fileContent[i] = fgetc(file);
printf("%d ", fileContent[i]);
}
printf("\n");
printf("DEBUG: Contents of file are:\n%s\n", fileContent);
fclose(file);
printf("DEBUG: outString is pointing to 0x%x\n", outString);
*outString = fileContent;
}
The output is usually just a bunch of question mark diamond things (running in terminal) that match the length of the file with a few other random chars thrown in at the end. The chars at the end change every time the program is run.
kaylum was right, the solution was to:
rewind() after finding the file length in readFile()
remember to fclose() when done
write directly to outString instead of using fileContent
The final code of main.c comes out to be:
#include <stdio.h>
int fileLength(const char filePath[]);
void readFile(const char filePath[], char* outString);
int main()
{
char fileContents[fileLength("Files/test")];
readFile("Files/test", &fileContents);
printf("File contents:\n%s\n", fileContents);
return 0;
}
int fileLength(const char filePath[])
{
//Open the file
FILE* file;
if ((file = fopen(filePath, "r")) == NULL)
{
printf("ERROR: File (%s) cannot be opened.\n", filePath);
return -1;
}
//Find the length
fseek(file, 0, SEEK_END);
int length = ftell(file);
fclose(file);
return length;
}
void readFile(const char filePath[], char* outString)
{
FILE* file;
//File reading
if ((file = fopen(filePath, "r")) == NULL)
{
printf("ERROR: File (%s) cannot be opened.\n", filePath);
exit(1);
}
//Get length of file and allocate the according amount of memory
fseek(file, 0, SEEK_END);
int fileLength = ftell(file);
rewind(file);
//Read file to string
for (int i = 0; i < fileLength; i++)
outString[i] = fgetc(file);
fclose(file);
}

why is my XOR operation only implemented on half of my text file

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 do I count the number of characters in a file?

I have copied the contents of a file to another file and I am trying to get the line, word, and character count. The code I have right now displays the number of lines and words in the file content. Now I need to display the character count but I am unsure of how to do that. I am guessing a for loop? But I am not sure.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MAX_WORD_LEN 100
#define MAX_LINE_LEN 1000
#define ipsumFile "Lorem ipsum.txt"
#define ipsumCopy "Lorem ipsum_COPY.txt"
int wordCount(FILE *fp);
int charCount(FILE *fp);
int sendContentTo(FILE *fp, FILE *out);
int getWordAt(FILE *fp, int pos, char *word);
int appendToFile(char *fileName, char *newText);
int main(void)
{
FILE *fp, *fp2; //"file pointer"
int ch; //place to store each character as read
//open Lorem ipsum.txt for read
if ((fp = fopen(ipsumFile, "r")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumFile);
exit(EXIT_FAILURE);
}
//open Lorem ipsumCopy for writing
if ((fp2 = fopen(ipsumCopy, "w+")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumCopy);
exit(EXIT_FAILURE);
}
//print out and count all words in Lorem ipsum.txt
int numOfWords = wordCount(fp);
//print out and count all lines in Lorem ipsum.txt
int numOfLines = sendContentTo(fp, stdout);
//copy the content of Lorem ipsum.txt into a new file (ipsumCopy)
numOfLines = sendContentTo(fp, fp2);
fclose(ipsumFile);
fclose(ipsumCopy);
// close Lorem ipsum.txt
if (fclose(fp) != 0)
fprintf(stderr, "Error closing file\n");
if (fclose(fp2) != 0)
fprintf(stderr, "Error closing copy\n");
return 0;
}
int sendContentTo(FILE *in, FILE *out)
{
fprintf(stdout, "Performing file copy...\n\n");
//start at the beginning of the file
rewind(in);
// array to hold one line of text up to 1000 characters
char line[MAX_LINE_LEN];
int lineCount = 0;
// read one line at a time from our input file
while (fgets(line, MAX_LINE_LEN, in) != NULL)
{
//send line we just read to output.
fprintf(out, "%s", line);
//count the lines
lineCount++;
}
fprintf(stdout, "\nFinished line count.\n");
fprintf(stdout, "Count is: %d.\n\n", lineCount);
// Return how many text lines
// we've processed from input file.
return lineCount;
}
// Read content from file one character at a time.
// Returns number of total characters read from the file.
int charCount(FILE *fp)
{
fprintf(stdout, "Performing char count...\n\n");
rewind(fp);
int charCount = 0;
char ch;
//print out each character, and return the
// number of characters in the file.
fprintf(stdout, "\nFinished character count. \n");
fprintf(stdout, "Count is: %d. \n\n", charCount);
return charCount;
}
// Read content from file one word at a time.
// Returns number of total words read from the file.
int wordCount(FILE *fp)
{
fprintf(stdout, "Performing word count...\n\n");
rewind(fp);
char word[MAX_WORD_LEN];
int wordCount = 0;
while (fscanf(fp, "%s", word) == 1)
{
// Send entire word string
// we just read to console
puts(word);
//count the word
wordCount++;
}
fprintf(stdout, "\nFinished word count.\n");
fprintf(stdout, "Count is: %d.\n\n", wordCount);
return wordCount;
}
You don't need to write different function for counting the number of lines, words, and characters in a file. You can do it in a single parsing of file character by character and while parsing, in order to copy the content of file to another file, you can write the characters to another file. You can do:
#include <stdio.h>
#include <stdlib.h>
int count_and_copy(const char * ipsumFile, const char * ipsumCopy)
{
unsigned int cCount = 0, wCount = 0, lCount = 0;
int incr_word_count = 0, c;
FILE *fp, *fp2;
if ((fp = fopen(ipsumFile, "r")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumFile);
exit(EXIT_FAILURE);
}
if ((fp2 = fopen(ipsumCopy, "w+")) == NULL)
{
fprintf(stdout, "Can't open %s file.\n", ipsumCopy);
exit(EXIT_FAILURE);
}
while((c = fgetc(fp)) != EOF)
{
fputc(c, fp2); // write character c to the copy file
cCount++; // character count
if(c == '\n') lCount++; // line count
if (c == ' ' || c == '\n' || c == '\t')
incr_word_count = 0;
else if (incr_word_count == 0) {
incr_word_count = 1;
wCount++; // word count
}
}
fclose (fp);
fclose (fp2);
printf ("Number of lines : %u\n", lCount);
printf ("Number of words : %u\n", wCount);
printf ("Number of characters : %u\n", cCount);
return 0;
}
int main()
{
/* Assuming, you want to count number of lines, words
* and characters of file1 and copy the contents of file1
* to file2.
*/
count_and_copy("file1", "file2");
return 0;
}
I suppose that the following approach will work:
void *cw(const char *fname)
{
FILE *f = fopen(fname, "r");
if (f == NULL) {
fprintf(stderr, "fopen(%s): %s\n", fname, strerror(errno));
exit(EXIT_FAILURE);
}
int bc = 0; /* bytes counter */
int wc = 0 ; /* words counter */
int nlc = 0; /* new lines counter */
const int in_word_state = 0;
const int out_word_state = 1;
int state = out_word_state;
int c = 0;
for (;;) {
c = fgetc(f);
if (ferror(f) != 0) {
perror("fgetc");
goto error;
}
if (feof(f))
break;
if (c == '\n')
nlc++;
if (c == ' ' || c == '\t' || c == '\n')
state = out_word_state;
if (state == out_word_state) {
state = in_word_state;
wc++;
}
bc++;
}
if (fclose(f) == EOF) {
perror("fclose");
goto error;
}
printf("w: %d, c: %d, l:%d\n", wc, bc, nlc);
error:
if (f != NULL) {
if (fclose(f) == EOF) {
perror("fclose");
}
}
exit(EXIT_FAILURE);
}

i am trying to read the values stored inside the buffer but instead its showing me the address?

i want to print the values in the location not the address..
when i run the program using breakpoint it does increases the values but doesn't print the values contained in the addresses..
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "conio.h"
int main()
{
char ch;
char buffer[100];
char* p;
p = buffer;
FILE *fp;
fp = fopen("D:\\Telenor_Short_01.vts","rb");// binary mode
fseek(fp,0,SEEK_END); //sets the file position of the stream to the given offset
int size=ftell(fp); //returns the current file position of the given stream.
printf("size of file is :%d\n",size);
if( fp == NULL ) //error checking
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
fread(p,1,100,fp);
for (int i=0;i<100;i++)
{
printf("%04x\n",*p);
p++;
}
fclose(fp);
/*printf("The contents of %s file are :\n", file_name);*/
/*int i;
while( ( ch = fgetc(fp) ) != EOF )
{
printf("%02X ",ch);
if( !(++i % 16) ) putc('\n', stdout);
}
fclose(fp);
putc('\n', stdout);*/
_getch();
return 0;
}
this is the output:
size of file is :185153907
5bf894
5bf895
5bf896
5bf897
5bf898
5bf899
5bf89a
5bf89b
5bf89c
5bf89d
5bf89e
5bf89f
5bf8a0
5bf8a1
5bf8a2
5bf8a3
5bf8a4
5bf8a5
5bf8a6
5bf8a7
5bf8a8
5bf8a9
5bf8aa
5bf8ab
5bf8ac
5bf8ad
5bf8ae
5bf8af
5bf8b0
5bf8b1
5bf8b2
5bf8b3
5bf8b4
5bf8b5
5bf8b6
5bf8b7
5bf8b8
5bf8b9
5bf8ba
5bf8bb
5bf8bc
5bf8bd
5bf8be
5bf8bf
5bf8c0
5bf8c1
5bf8c2
5bf8c3
5bf8c4
5bf8c5
5bf8c6
5bf8c7
5bf8c8
5bf8c9
5bf8ca
5bf8cb
5bf8cc
5bf8cd
5bf8ce
5bf8cf
5bf8d0
5bf8d1
5bf8d2
5bf8d3
5bf8d4
5bf8d5
5bf8d6
5bf8d7
5bf8d8
5bf8d9
5bf8da
5bf8db
5bf8dc
5bf8dd
5bf8de
5bf8df
5bf8e0
5bf8e1
5bf8e2
5bf8e3
5bf8e4
5bf8e5
5bf8e6
5bf8e7
5bf8e8
5bf8e9
5bf8ea
5bf8eb
5bf8ec
5bf8ed
5bf8ee
5bf8ef
5bf8f0
5bf8f1
5bf8f2
5bf8f3
5bf8f4
5bf8f5
5bf8f6
5bf8f7
but i want the values ..
First, check fp for NULL immediately after fopen. Second seek to the beginning of the file before fread. Last, most importantly, check the return value of fread, because that's the number of elements that was read into the buffer. It may be smaller than the buffer.
fp = fopen("D:\\Telenor_Short_01.vts","rb");// binary mode
if( fp == NULL ) //error checking
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
fseek(fp,0,SEEK_END); //sets the file position of the stream to the given offset
int size=ftell(fp); //returns the current file position of the given stream.
printf("size of file is :%d\n",size);
fseek(fp, 0, SEEK_SET);
int nread = fread(p, 1, 100, fp);
for (int i=0; i<nread; i++)
{
printf("%04x\n", *p);
p++;
}
fclose(fp);
In addition, in C, you can access array elements either by subscription or by pointers arithmetic, the two are the same effect:
char arr[8];
arr[3] is same as *(arr + 3);
&arr[3] is same as arr + 3;
To read the big file by chunks:
fseek(fp, 0, SEEK_SET);
char buf[4096];
int nread;
int i;
while (1) {
nread = fread(buf, 1, 4096, fp);
for (i=0; i<nread; i++)
{
printf("%02x\n", buf[i]);
}
if (nread < 4096)
break;
}
fclose(fp);

Writing to a text file through the CMD window and a C exe?

I was wondering how I can get this code to overwrite a textfile from it's text value to it's ASCII value.
I want it to do something like this:
CMD > c:\users\username\desktop>cA5.exe content.txt
content.txt has "abc" in it and I want the command line to change the "abc" to it's ASCII values. 97... etc. I don't want anything written in the command window, I want it to change in the text file. Is this possible, if so, how could I do it with this existing code?
#include <stdio.h>
#include <stdlib.h>
int main(int argc[1], char *argv[1])
{
FILE *fp; // declaring variable
fp = fopen(argv[1], "rb");
if (fp != NULL) // checks the return value from fopen
{
int i;
do
{
i = fgetc(fp); // scans the file
printf("%c",i);
printf(" ");
}
while(i!=-1);
fclose(fp);
}
else
{
printf("Error.\n");
}
}
Not the best code but very simple.
#include <stdio.h>
#include <stdlib.h>
void convertToAHex(char *data, long int size, FILE *file){
rewind(file);
int i;
for(i = 0; i < size; ++i){
fprintf(file, "%d ", data[i]);
}
}
int main(int argc, char *argv[]){
if(argc != 2){
return EXIT_FAILURE;
}
FILE *file = fopen(argv[1], "r+");
if(file){
char *data;
long int size;
fseek(file, 0, SEEK_END);
size = ftell(file);
rewind(file);
data = (char *) calloc(size, sizeof(char));
if(data){
fread(data, 1, size, file);
convertToAHex(data, size, file);
free(data);
}
fclose(file);
}
return EXIT_SUCCESS;
}

Resources