copy a text file using c - c

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

Related

Reading reads strings from keyboard and writing them to a file

Here's my task and below you can find my specific question and the code I wrote:
Write a program that reads strings and writes them to a file. The string must be dynamically
allocated and the string can be of arbitrary length. When the string has been read it is written to the
file. The length of the string must be written first then a colon (‘:’) and then the string. The program
stops when user enters a single dot (‘.’) on the line.
For example:
User enters: This is a test
Program writes to file: 14:This is a test
Question:
My code adds the number of characters and the colon, but not the string I typed, and when entered "." it wont exit
This is the code I have so far:
#pragma warning(disable: 4996)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_SZ 256
int main() {
char key[] = ".";
char *text;
int i;
text = (char*)malloc(MAX_NAME_SZ);
FILE* fp;
do {
printf("Enter text or '.' to exit: ", text);
fgets(text, MAX_NAME_SZ, stdin);
for (i = 0; text[i] != '\0'; ++i);
printf("%d: %s", i);
fp = fopen("EX13.txt", "w");
while ((text = getchar()) != EOF) {
putc(text, fp);
}
fclose(fp);
printf("%s\n", text);
} while (strncmp(key, text, 1) != 0);
puts("Exit program");
free(text);
return 0;
}
There are many issues in your code, almost everything is wrong.
Just a few problems:
You use printf("%d: %s", i); to print on the screen what should go into the file.
The loop while ((text = getchar()) != EOF) doesn't make any sense.
You're closing the file after the first line entered
You ignore all compiler warnings
The end condition while (strncmp(key, text, 1) != 0) is wrong, you're only testing if the string starts with a ., and you're testing it too late.
This could be a start:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_SZ 256
int main() {
char* text;
int i;
text = (char*)malloc(MAX_NAME_SZ);
FILE* fp;
fp = fopen("EX13.txt", "w");
if (fp == NULL)
{
printf("Can't open file\n");
exit(1);
}
do {
printf("Enter text or '.' to exit: ");
fgets(text, MAX_NAME_SZ, stdin);
if (strcmp(".\n", text) == 0)
break;
for (i = 0; text[i] != '\0' && text[i] != '\n'; ++i);
fprintf(fp, "%d: %s", i, text);
} while (1);
fclose(fp);
puts("Exit program");
free(text);
return 0;
}
There is a limitation though, in this program the maximum line length is 254 characters, not including the newline character. As far as I understood, the line length must be arbitrary.
I let you do this on your own as an exercise, but at your C knowledge level it will be hard.
I think this should work for strings that are shorter than 255 chars.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_SZ 256
int main()
{
char key[] = ".\n";
char *text;
text = (char*)malloc(MAX_NAME_SZ);
if (text == NULL)
{
perror("problem with allocating memory with malloc for *text");
return 1;
}
FILE *fp;
fp = fopen("EX13.txt", "w");
if (fp == NULL)
{
perror("EX13.txt not opened.\n");
return 1;
}
printf("Enter text or '.' to exit: ");
while (fgets(text, MAX_NAME_SZ, stdin) && strcmp(key, text))
{
fprintf(fp, "%ld: %s", strlen(text) - 1, text);
printf("Enter text or '.' to exit: ");
}
free((void *) text);
fclose(fp);
puts("Exit program");
return 0;
}

print 5 lines from input file

currently, I am writing code in c program for printing small portion of contents from the input file. Actually, in my code I can able to print just one single line. but, i have to print next 5 lines after that one line.
I am new to programming, please help to solve this problem**
code is given below
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int lineNumber = 2;
int main()
{
FILE *file;
char line[100];
int count = 0;
///Open LS-dyna file to read
file = fopen("P:\\tut_c\\read\\df-read\\in.txt", "r");
if (file == NULL)
{
perror("fopen");
exit(EXIT_FAILURE);
}
else if ( file != NULL )
{
char line[256];
while (fgets(line, sizeof line, file) != NULL)
{
if (count == lineNumber)
{
printf("\n str %s ", line);
fclose(file);
return 0;
}
else
{
count++;
}
}
fclose(file);
}
return 0;
}
The first logical error occurs in your while loop, first iteration, when you close the file and return 0.
Next, there is no reason to have a counter for your lines, since there are many c functions that can handle finding the end of file (eof).
Instead:
Use a while loop for iteration through the file.
Use a standard library c function for file reading.
Check if file has reached the end.
If the line is still valid, then print the line.
Here is some code to reiterate:
int main()
{
FILE *file;
file = fopen("file.txt", "r");
if (!file){ // check if file exists
perror("fopen");
exit(EXIT_FAILURE);
}
else { // if file exists, then...
char line[256];
while(fgets(line, sizeof line, file)){
printf("\n str %s ", line);
}
fclose(file);
}
return 0;
}// end main

How to scan a string and write it in a file?

I want to scan a string that a user inputs, then write it into the file (file.txt), but this doesn't seem to work for some reason
int main()
{
FILE *stream;
stream = fopen("file.txt", "w");
char str[] = { '\0 ' };
scanf("%s", &str);
fprintf(stream, "%s.\n", str);
fclose(stream);
return(0);
}
try this, should work just fine.
It did for me so it should for you too.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *stream;
stream = fopen("ceva.txt", "w");
if (stream == NULL) {
perror("Failed: ");
return 1;
}
char str[250];
scanf("%249s", str);
fprintf(stream, "%s.\n", str);
fclose(stream);
return 0;}
You must change scanf with fscanf

Why is my_getline() causing a system hang?

This program attempts to save the contents of a text file into a character variable array. It is then supposed to use my_getline() to print the contents of the character array. I've tested and see that the contents are in fact getting saved into char *text but I can't figure out how to print the contents of char *text using my_getline(). my_getline is a function we wrote in class that I need to use in this program. When I attempt to call it in the way that was taught, it 1 is printed to terminal but then the terminal just waits and nothing else is printed. Any guidance would be appreciated. Also, let me know if I'm missing any information that would help.
/* Include the standard input/output and string libraries */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Define the maximum lines allowed in an input text and NEWLINE for getline funct. */
#define MAXPATTERN 15
#define MAXFILENAMELENGTH 15
#define NEWLINE '\n'
/* function prototypes */
void my_getline(char text[]);
int find_string(char text[], char pattern[], int length_text, int length_pattern);
int main()
{
FILE *fp;
long lSize;
char *text;
char fileName[MAXFILENAMELENGTH], pattern[MAXPATTERN];
char c;
int length_text, length_pattern, j, lineNumber = 1;
printf("Enter file name: ");
scanf("%s", fileName);
fp = fopen(fileName, "r");
if (fp == NULL)
{
printf("fopen failed.\n");
return(-1);
}
fseek(fp, 0L, SEEK_END);
lSize = ftell(fp);
rewind(fp);
/* allocate memory for all of text file */
text = calloc(1, lSize + 2);
if(!text)
{
fclose(fp);
fputs("memory allocs fails", stderr);
exit(1);
}
/* copy the file into text */
if(1 != fread(text, lSize, 1, fp))
{
fclose(fp);
free(text);
fputs("Entire read fails", stderr);
exit(1);
}
text[lSize + 1] = '\0';
printf("%s has been copied.\n", fileName);
rewind(fp);
printf("%d ", lineNumber);
for (j = 0; (j = getchar()) != '\0'; j++)
{
my_getline(text);
printf("%d %s\n", j+1, text);
}
printf("Enter the pattern you would like to search for: ");
scanf("%s", pattern);
printf("\nYou have chosen to search for: %s\n", pattern);
fclose(fp);
free(text);
return(0);
}
void my_getline(char text[])
{
int i = 0;
while ((text[i] = getchar()) != NEWLINE)
++i;
text[i] = '\0';
}
Your function is causing a system hang because you're calling getchar(), which returns the next character from the standard input. Is this really what you want?
At this point, your program is expecting input from the user. Try typing in the console windows and pressing to see it coming back from the "hang"
It is most likely causing an infinite loop because you are not checking whether you have reached EOF.
void my_getline(char text[])
{
int i = 0;
int c;
while ( (c = getchar()) != NEWLINE && c != EOF )
text[i++] = c;
text[i] = '\0';
}

reading a string from a file

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;
}

Resources