int main()
{
FILE *infile;
FILE *infile2;
char input[255],input2[255];
int status1, status2;
infile = fopen("test.txt", "r");
infile2 = fopen("test2.txt", "r");
if(infile == NULL)
{
printf("Can not open file 1!\n");
}
else if(infile2 == NULL)
{
printf("Can not open file 2!\n");
}
else
{
do
{
status1 = fscanf(infile, "%s", &input);
status2 = fscanf(infile2, "%s", &input2);
printf("File 1: %s\n File 2: %s\n", input, input2);
}while(status1 != -1 || status2 != -1);
}
fclose(infile);
fclose(infile2);
return 0;
}
My output looks like this:
Output
I would like to print out file 1 in one line not word by word. The same goes for file2. I'm kinda new to C so I'm stuck.
If you would like to read the entire line, use fgets function instead of fscanf:
char *status1, *status2;
.
.
.
do {
status1 = fgets(input, sizeof(input), infile);
status2 = fgets(input2, sizeof(input2), infile2);
printf("File 1: %s File 2: %s", input, input2);
} while (status1 || status2);
Note how printf no longer uses \n. This is because fgets keeps \n from the file inside your input string.
I made the changes to the code and it works, but another question. If i wanted to compare the files and write out the differnce to a new file like this:
File1: My name is Knut
File2: My name is KnutAndre
File3: Andre (This is the differnce between the files).
My teacher told me to use strcmp and then get the output into a new file, but i dont quite understand him.. Does anyone have some tips that i could try out?
This is how my code look so far:
int main()
{
FILE *infile;
FILE *infile2;
FILE *outfile3;
char input[255],input2[255];
char status1, status2;
infile = fopen("test.txt", "r");
infile2 = fopen("test2.txt", "r");
if(infile == NULL)
{
printf("Can not open file 1!\n");
}
else if(infile2 == NULL)
{
printf("Can not open file 2!\n");
}
else
{
do
{
status1 = fgets(input, sizeof(input), infile);
status2 = fgets(input2, sizeof(input2), infile2);
if(status1 != 0){
printf("File 1: %s\n\nFile 2: %s\n\n", input, input2);
int result = strcmp(input, input2);
printf("\nResult = %d\n\n", result);
}
}
while(status1 || status2);
}
fclose(infile);
fclose(infile2);
return 0;
}
When you are using the fscanf it will only read the characters until the non white space character occurs. When you need to get the input as whole line then you have to use fgets().
From the man page of fgets().
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character
in the buffer.
So you have to use like this.
fgets(input,255,infile);
fgets(input2,255,infile2);
While checking condition,
while(input != NULL || input2 != NULL);
In my school, we make a get_next_line function, who takes a file descriptor and a pointer to a string in parameter.
you can take a look here : https://github.com/juschaef/libtowel/search?utf8=%E2%9C%93&q=get+next+line
Related
I have this code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* ptr = fopen("data.txt","r");
char filename[100];
if (ptr==NULL)
{
printf("no such file.");
return 0;
}
char buf[100];
while (fscanf(ptr,"%*s %*s %s ",buf)==1)
printf("%s\n", buf);
printf("Create a file \n");
scanf("%s", filename);
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
}
It coppies full content from one file to another. I need to copy only strings that have 5 as the last character (3 column)
For example Data.txt looks like that:
Alex 10B 4
John 10A 3
Kate 10C 5
In file that I will create during execution has to be coppied only Kate 10C 5 string. I've been trying for hours but I don't know how to do this. Can you help me?
In the end of each line there is a newline character, (\n) you can use that to read line by line and copy only the ones that you want:
FILE* dest = fopen("out.txt", "w+"); // supressed null check for simplicity
char buf[100];
char* char_to_find;
// parse line by line
while (fscanf(ptr, " %99[^\n]", buf) == 1){
char_to_find = buf;
// reach the end of the line
while(*char_to_find){
char_to_find++;
}
//move one back
char_to_find--;
// if it's 5 save, if not move on
if(*char_to_find == '5' && *(char_to_find - 1) == ' '){
fputs(buf, dest);
}
}
Live demo
The problem is that the function call
while (fscanf(ptr,"%*s %*s %s ",buf)==1)
consumes the input from the input stream, so that it is no longer available for copying. You are only saving the contents of the last field, but all other data is lost.
I suggest that you read one line at a time into a memory buffer, by calling the function fgets in a loop. That way, you will process one line of input per loop iteration, and will be saving the contents of the entire line.
In every loop iteration, you can use sscanf on this memory buffer to determine whether the third field has the desired value, and if it does, then you copy the entire line to the output file. Otherwise, you do nothing and proceed to the next line (i.e. the next loop iteration).
char line[100];
//process one line of input per loop iteration
while ( fgets( line, sizeof line, input_file ) != NULL )
{
char third_field[20];
if (
//third field was successfully extracted
sscanf( line, "%*s%*s%19s", third_field ) == 1
&&
//third field contains the string "5"
strcmp( third_field, "5" ) == 0
)
{
//copy entire line to output file
fputs( line, output_file );
}
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* ptr = fopen("data.txt","r");
char filename[100];
if (ptr==NULL)
{
printf("no such file.");
return 0;
}
printf("Create a file \n");
scanf("%s", filename);
FILE* dest = fopen(filename, "w+"); // check for null like above
char buf[100];
char* char_to_find;
while (fscanf(ptr,"%99[^\n] ", buf) == 1){
char_to_find = buf;
while(*char_to_find != 0){
char_to_find++;
}
char_to_find--;
if(*char_to_find == '5'){
printf("%s\n", buf); // test ptint
fputs(buf, dest);
}
}
}
I've used a ".txt" extension while reading and writing the file, also the file mode is corresponding to that of "text" type of file. The program runs fine, but instead of storing an ASCII character in the file, it is storing binary characters. I need some assistance here. Thank you.
int main(void)
{
FILE *fp;
int n2, n1;
printf("ENTER A NUMBER: ");
scanf("%d", &n1);
fp = fopen("hello.txt", "w");
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
fprintf(fp, "%d", n1);
//fclose(fp);
//rewind(fp);
fp = fopen("hello.txt", "r");
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
//n2 = getw(fp);
fscanf(fp, "%d", n1);
printf("%d", n1);
fclose(fp);
}
If you are going to close and reopen the file you don't need rewind. Or you can open the file to read and write, and then you can use rewind. Both work, here is a sample of the latter:
int main(void)
{
FILE *fp;
int n2, n1;
printf("ENTER A NUMBER: ");
if (scanf("%d", &n1) == 1) // checking if the input was correctly parsed
{
fp = fopen("hello.txt", "w+"); // open to read and write
if (fp == NULL)
{
printf("ERROR");
exit(1);
}
putw(n1, fp); // write to the file
rewind(fp); // go back to the beginning of the file
n2 = getw(fp); // get the data
printf("%d", n2);
fclose(fp);
}
else
{
puts("Bad input");
}
}
Live sample
There is still the matter of possible integer overflow when reading from stdin, if there is no requirement to guard against that, make sure to at least document the vulnerability, otherwise the advice is to use fgets to read input and strtol to convert the value.
You should send address of a variable in fscanf, like this:
fscanf(fp,"%d",&n1);
For an assignment I have to input text from 2 files line by line into a 3rd file. So file 1 line 1 would be file 3 line 1 and file 2 line would would be file 3 line 2. I have attempted to this but can not seem to get the lines from each file to alternate. I am only able to get lines from each file separately. Please help with any suggestions.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *file1, *file2, *file3;
char line [1000]; /* or other suitable maximum line size */
// check to make sure that all the file names are entered
if (argc != 4) {
perror("Error: ");
printf("Not enough files were entered!\n");
exit(0);
}
file1 = fopen(argv[1],"r");;
file2 = fopen(argv[2],"r");
file3 = fopen(argv[3],"w");
// check whether the file has been opened successfully
if (file1 == NULL)
{
perror("Error: ");
printf("Cannot open file1 %s!\n", argv[1]);
exit(-1);
}
// check whether the file has been opened successfully
if (file2 == NULL)
{
perror("Error: ");
printf("Cannot open file2 %s!\n", argv[2]);
exit(0);
}
// check whether the file has been opened successfully
if (file3 == NULL)
{
perror("Error: ");
printf("Cannot open file3 %s!\n", argv[3]);
exit(0);
}
int count = 0;
while (1)
{
if(fgets(line, sizeof line, file1) != NULL)
{
count+=1;
fprintf(file3, line);
}
else
{
break;
}
if(fgets(line, sizeof line, file2) != NULL)
{
count++;
fprintf(file3, line);
}
else
{
break;
}
}
fclose (file1);
fclose (file2);
fclose (file3);
}
fprintf(FILE *, const char *format, ...) expects a format as the 2nd argument.
Using fprintf(file3, line); will invoke undefined behavior (UB) should line contain a '%' or at least a missing % if "%%" was encountered.
Use fputs()
// fprintf(file3, line);
fputs(line, file3);
Additional concerns for advanced coding:
If the source file contains a null character, using fgets() is insufficient as it does not report the length read. Other approaches include using fgetc(), fread() or non-standard C getline().
If an input file does not end with a '\n', that rump line may look like a pre-fix to the line read from the other file.
As OP has noted, line length's of about 1000+ are a problem.
Source files line-endings, should they not match the code's understanding of line-ending can cause issues.
I am having problems with copying txt files. I need to info from one file to another.
My code looks like this,
_tprintf (TEXT("%s\n"), FindFileData.cFileName);
memset(fileName, 0x00, sizeof(fileName));
_stprintf(fileName, TEXT("%s\\%s"), path, FindFileData.cFileName); //iegust
FILE *fptr = fopen(fileName, "r");//atver
fscanf(fptr,"%[^\n]",c); //iegust datus no faila
printf("Data from file:\n%s",a);
strcpy(a, c); //nokope datus
buffer2 = strtok (c, ","); //norada partraukumu un tadas lietas
while (buffer2) {
buffer2 = strtok (NULL, ",");
if(i<1){ printf("%s\n", c);}
i++;
while (buffer2 && *buffer2 == '\040'){
buffer2++;
// TODO ieliec iekavinas
}
}
And after that I use basic fputs().
My problem is that this code ignores new lines. It prints out fine, each string in it's own line, but that does not happen in file. (\n).
Your problem is that you just need to copy information from one file to another. So, why you don't use a simple solution to do it than your. I have a snipet code can solve your problem easily as shown below.
If I am wrong about your question, please give me advices.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
So i've been given an exercise to work on: Have the user input a number and the program will display the line of text associated with that line for example
Password
abcdefg
Star_wars
jedi
Weapon
Planet
long
nail
car
fast
cover
machine
My_little
Alone
Love
Ghast
Input 3: Output: Star_wars
Now i have been given a program to solve this, however it uses the function getline() , which doesn't complie on DEV C++.
#include <stdio.h>
int main(void)
{
int end = 1, bytes = 512, loop = 0, line = 0;
char *str = NULL;
FILE *fd = fopen("Student passwords.txt", "r");
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
printf("Enter the line number to read : ");
scanf("%d", &line);
do {
getline(&str, &bytes, fd);
loop++;
if (loop == line)
end = 0;
}while(end);
printf("\nLine-%d: %s\n", line, str);
fclose(fd);
}
All i need is to know how to do this, in a simple program without the use of getline()
Thanks
Edit: I also don't want to download software to make this work
use fgets instead of getline.
#include <stdio.h>
int main(void){
int end, loop, line;
char str[512];
FILE *fd = fopen("data.txt", "r");
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
printf("Enter the line number to read : ");
scanf("%d", &line);
for(end = loop = 0;loop<line;++loop){
if(0==fgets(str, sizeof(str), fd)){//include '\n'
end = 1;//can't input (EOF)
break;
}
}
if(!end)
printf("\nLine-%d: %s\n", line, str);
fclose(fd);
return 0;
}
You have wrote:
char *str = NULL;
and you used it without initializing:
getline(&str, &bytes, fd);
first you must initialize it:
char *str=(char*)malloc(SIZEOFSTR);
you can add this part in your program instead of your do-while loop. You will be using fscanf() whose arguments are the file pointer, specifier of data type and the variable you want to store.
printf("Enter the line number to read : ");
scanf("%d", &line);
while(line--) {
fscanf(fd,"%s",str);
}
printf("\nLine-%d:%s\n",line,str);